Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid preRenderView method call in ajax request?

Tags:

jsf-2

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?

like image 414
Arun Avatar asked Feb 04 '13 13:02

Arun


1 Answers

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.
            }
    
like image 164
BalusC Avatar answered Jan 04 '23 03:01

BalusC