Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
962 views
in Technique[技术] by (71.8m points)

jsf 2 - How to avoid preRenderView method call in ajax request?

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...