Is there a way to call a method upon leaving a page with JSF or PrimeFaces?

送分小仙女□ 提交于 2019-12-03 18:02:40

问题


Is there a way to call a method upon leaving a page with JSF?


回答1:


Not when using native JSF or PrimeFaces. Your best bet would be to hook on session expiration instead.

import javax.inject.Named;
import javax.enterprise.context.SessionScoped;

@Named
@SessionScoped
public class Bean implements Serializable {

    @PreDestroy
    public void destroy() {
        // Your code here.
    }
}

If you happen to use the JSF utility library OmniFaces, then you can use its @ViewScoped. This will call the @PreDestroy when leaving the page referencing the view scoped bean.

import javax.inject.Named;
import org.omnifaces.cdi.ViewScoped;

@Named
@ViewScoped
public class Bean implements Serializable {

    @PreDestroy
    public void destroy() {
        // Your code here.
    }
}

Under the covers, it works by triggering a navigator.sendBeacon() during the window beforeunload event with a fallback to synchronous XHR (which is deprecated in modern browsers supporting navigator.sendBeacon()).

See also:

  • How detect and remove (during a session) unused @ViewScoped beans that can't be garbage collected



回答2:


If you use omnifaces @ViewScoped annotation in the backing bean the bean object is destroyed when you leave the view; so you can call a function when this happens using the @PreDestroy annotation in it.

Note: You must use omnifaces @ViewScoped annotation; with standard JSF @ViewScoped annotation the object isn't destroyed just by leaving the view, so pay attention to the import!

Source: http://showcase.omnifaces.org/cdi/ViewScoped




回答3:


Your problem Solution :- it work with java script

    <head>
<title>onunload test</title>
<script type="text/javascript">
window.onunload = unloadPage;

function unloadPage()
{
 alert("unload event detected!");
}
</script>
</head>

Also Some link for more details:- Link




回答4:


You can call a JSF managed bean method when you are closing the page or navigating to another page by using a <a4j:jsFunction/> and calling it at 'onunload' event of the page body as below.

<body onunload="leavingPage()">

<a4j:jsFunction name="leavingPage" action="#{myBean.myMethod}"/>


来源:https://stackoverflow.com/questions/9983904/is-there-a-way-to-call-a-method-upon-leaving-a-page-with-jsf-or-primefaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!