如何避免ajax请求中的preRenderView方法调用? [英] How to avoid preRenderView method call in ajax request?

查看:97
本文介绍了如何避免ajax请求中的preRenderView方法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在页面加载时在支持bean中调用一个方法.我使用

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

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

但是只要在页面中发出ajax请求,该方法就会再次被调用.我不需要它.如何避免Ajax请求中的方法调用?

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?

推荐答案

在呈现视图之前,仅对每个请求调用preRenderView事件. Ajax请求也是呈现视图的请求.因此,这种行为是完全可以预期的.

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.

您基本上有2个选择:

  1. 通过@PostConstruct方法将其替换为@ViewScoped bean.

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

@ManagedBean
@ViewScoped
public class ManagedBean {

    @PostConstruct
    public void onLoad() {
        // ...
    }

}

然后仅在首次构造Bean时才调用它.只要您通过回发(无论是否使用Ajax)与同一个视图进行交互,视图范围的Bean实例就可以存在.

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.

如果当前请求是ajax请求,请在侦听器方法中执行检查.

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

        // ...
    }

}

或者,如果您实际上对跳过回发而不是专门针对ajax请求感兴趣,那么请这样做:

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

这篇关于如何避免ajax请求中的preRenderView方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆