3

Is there any way to handle page unLoad event in JSF 2.0? I want to perform some data reset whenever the user move away from a particular page?

user1220373
  • 383
  • 1
  • 9
  • 19

1 Answers1

4

There is no 100% reliable way to inform the server side about the unload event. Depending on the browser make/version, either the server cannot be hit by an ajax (XMLHttpRequest) request at all, or you'll run into a race condition if the ajax request can ever be successfully completed (because the ajax request is abruptly been aborted because the tab/window is been closed, and thus you risk that the server never retrieves the complete ajax request).

Your best bet is to hook on destroy events in the server side. E.g. in case of a @ViewScoped bean you just have to create a method annotated with @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.
    }

}

Or maybe you don't need it at all. You just need to store the data as a property of a view scoped bean instead of a session scoped bean. Developers who are abusing session scoped beans have namely very often this kind of requirement ;) See also How to choose the right bean scope?

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555