16

I need to call a method in backing bean while the page loads. I achieved it using

<f:event listener="#{managedBean.onLoad}" type="preRenderView">

But whenever an ajax request is made in the page, that method get invoked again. I don't need it in my requirement. How to avoid that method call in ajax request?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Arun
  • 825
  • 4
  • 14
  • 31

1 Answers1

30

The preRenderView event is just invoked on every request before rendering the view. An ajax request is also a request which renders a view. So the behavior is fully expected.

You've basically 2 options:

  1. Replace it by @PostConstruct method on a @ViewScoped bean.

    @ManagedBean
    @ViewScoped
    public class ManagedBean {
    
        @PostConstruct
        public void onLoad() {
            // ...
        }
    
    }
    

    This is then only invoked when the bean is constructed for the first time. A view scoped bean instance lives as long as you're interacting with the same view across postbacks, ajax or not.


  2. Perform a check inside the listener method if the current request is an ajax request.

    @ManagedBean
    // Any scope.
    public class ManagedBean {
    
        public void onLoad() {
            if (FacesContext.getCurrentInstance().getPartialViewContext().isAjaxRequest()) { 
                return; // Skip ajax requests.
            }
    
            // ...
        }
    
    }
    

    Or, if you're actually interested in skipping postbacks instead of specifically ajax requests, then do so instead:

            if (FacesContext.getCurrentInstance().isPostback()) { 
                return; // Skip postback requests.
            }
    
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks for your answer, But my Backing Bean needs to be session scoped... how can I handle this??? – Arun Feb 05 '13 at 04:39
  • Then go for the 2nd approach. – BalusC Feb 05 '13 at 09:27
  • Hi @BalusC, what does it means when you say: "A view scoped bean instance lives as long as you're interacting with the same view across postbacks, ajax or not."? I have a scenario where I have a view scope bean, I have a button on a datatable. When user clicks that button, it queries for some data and opens a form in the same view and the user has the option to return to the previous screen by clicking Return. All these occurs on the same index.xhtml view. When clicking Return, however, the postconstruct is firing. I checked a few SO questions/answers and haven't figure it out. Thoughts? – Erick Dec 20 '17 at 14:58
  • @BalusC, unfortunately I had read that link and found no answer. – Erick Dec 21 '17 at 14:16