4.6. Shutting Down an Application

A user can log out or close the web page or browser, so a session and the associated application instance can end. Ending an application can be initiated by the application logic. Otherwise, it will be ended automatically when the Servlet session times out.

4.6.1. Closing an Application

If the user quits the application through the user interface, an event handler should call the close() method in the Application class to shutdown the session.

In the following example, we have a Logout button, which ends the user session.

Button closeButton = new Button("Logout");

closeButton.addListener(new Button.ClickListener() {
    @Override
    public void buttonClick(ClickEvent event) {
        getMainWindow().getApplication().close();
    } 
});

main.addComponent(closeButton);

You will soon notice that closing the application simply reloads the application with a new Application instance. You can set the window to redirect to a different URL (that does not reload the application) with setLogoutURL. In your application class, write:

setLogoutURL("/logout.html");

4.6.2. Handling the Closing of a Window

Closing the main window (or all application-level windows) does not close session and the application instance will be left hanging. You need to program such behaviour by handling the close events of the windows.

If the user closes a browser window, such as the main window or any other application-level window, the window will send a final AJAX request to the server, which will fire a Window.CloseEvent for the closed window. You can handle the event with a Window.CloseListener. In case the user closes the browser, the event is fired for every open window.

// Close the application if the main window is closed.
main.addListener(new Window.CloseListener(){
   @Override
    public void windowClose(CloseEvent e) {
       System.out.println("Main window closed - closing the application");
       getMainWindow().getApplication().close();
    } 
});

Notice that refreshing a window means closing and reopening it. Therefore, if you have a close handler as above, the user loses the possibility to refresh the browser window.

In the likely case that the browser crashes, no close event is communicated to the server. As the server has no way of knowing about the problem, and the session will be left hanging until the session timeout expires. During this time, the user can restart the browser, open the application URL, and the main window will be rendered where the user left off. This can be desired behaviour in many cases, but sometimes it is not and can create a security problem.