Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
936 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.
            }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...