JSF中的页面卸载事件处理

时间:2012-04-22 18:19:05

标签: jquery jsf-2

有没有办法在JSF 2.0中处理页面unLoad事件?我想在用户离开特定页面时执行一些数据重置?

1 个答案:

答案 0 :(得分:3)

没有100%可靠的方式来通知服务器端有关unload事件的信息。根据浏览器的品牌/版本,服务器根本不能被ajax(XMLHttpRequest)请求命中,或者如果ajax请求可以成功完成,你将遇到竞争条件(因为ajax)请求突然中止,因为选项卡/窗口已关闭,因此您可能会冒服务器永远不会检索完整的ajax请求。)

最好的办法是在服务器端挂钩销毁事件。例如。如果是@ViewScoped bean,您只需要创建一个用@PreDestroy注释的方法:

@ManagedBean
@ViewScoped
public class Bean {

    @PreDestroy
    public void destroy() {
        // This method is called whenever the view scope has been destroyed.
        // That can happen when the user navigates away by a POST which is
        // invoked on this bean, or when the associated session has expired.
    }

}

或许你根本不需要它。您只需将数据存储为视图范围bean而不是会话范围bean的属性。滥用会话范围bean的开发人员通常都是这种要求;)另见How to choose the right bean scope?

相关问题