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?
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:
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.
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With