Application Lifecycle

In this section, we look into more technical details of application deployment, user sessions, and UI instance lifecycle. These details are not generally needed for writing Vaadin applications, but may be useful for understanding how they actually work and, especially, in what circumstances their execution ends.

Deployment

Before a Vaadin application can be used, it has to be deployed to a Java web server, as described in “Deploying an Application”. Deploying reads the servlet classes annotated with the @WebServlet annotation (Servlet 3.0) or the web.xml deployment descriptor (Servlet 2.4) in the application to register servlets for specific URL paths and loads the classes. Deployment does not yet normally run any code in the application, although static blocks in classes are executed when they are loaded.

Undeploying and Redeploying

Applications are undeployed when the server shuts down, during redeployment, and when they are explicitly undeployed. Undeploying a server-side Vaadin application ends its execution, all application classes are unloaded, and the heap space allocated by the application is freed for garbage-collection.

If any user sessions are open at this point, the client-side state of the UIs is left hanging and an Out of Sync error is displayed on the next server request.

Redeployment and Serialization

Some servers, such as Tomcat, support hot deployment, where the classes are reloaded while preserving the memory state of the application. This is done by serializing the application state and then deserializing it after the classes are reloaded. This is, in fact, done with the basic Eclipse setup with Tomcat and if a UI is marked as @PreserveOnRefresh, you may actually need to give the ?restartApplication URL parameter to force it to restart when you reload the page. Tools such as JRebel go even further by reloading the code in place without need for serialization. The server can also serialize the application state when shutting down and restarting, thereby preserving sessions over restarts.

Serialization requires that the applications are serializable, that is, all classes implement the Serializable interface. All Vaadin classes do. If you extend them or implement interfaces, you can provide an optional serialization key, which is automatically generated by Eclipse if you use it. Serialization is also used for clustering and cloud computing, such as with Google App Engine.

For more about that topic, see “Google App Engine Integration”.

Vaadin Servlet, Portlet, and Service

The VaadinServlet, or VaadinPortlet in a portal, receives all server requests mapped to it by its URL, as defined in the deployment configuration, and associates them with sessions. The sessions further associate the requests with particular UIs.

When servicing requests, the Vaadin servlet or portlet handles all tasks common to both servlets and portlets in a VaadinService. It manages sessions, gives access to the deployment configuration information, handles system messages, and does various other tasks. Any further servlet or portlet specific tasks are handled in the corresponding VaadinServletService or VaadinPortletService. The service acts as the primary low-level customization layer for processing requests.

Customizing Vaadin Servlet

Many common configuration tasks need to be done in the servlet class, which you already have if you are using the @WebServlet annotation for Servlet 3.0 to deploy the application. You can handle most customization by overriding the servletInitialized() method, where the VaadinService object is available with getService() (it would not be available in a constructor). You should always call super.servletInitialized() in the beginning.

Java

  1. public class MyServlet extends VaadinServlet {
  2. @Override
  3. protected void servletInitialized()
  4. throws ServletException {
  5. super.servletInitialized();
  6. ...
  7. }
  8. }

To add custom functionality around request handling, you can override the service() method.

To use the custom servlet class in a Servlet 2.4 project, you need to define it in the web.xml deployment descriptor instead of the regular VaadinServlet class, as described in “Using a web.xml Deployment Descriptor”.

Customizing Vaadin Portlet

To Be Done

Customizing Vaadin Service

To customize VaadinService, you first need to extend the VaadinServlet or - Portlet class and override the createServletService() to create a custom service object.

User Session

A user session begins when a user first makes a request to a Vaadin servlet or portlet by opening the URL for a particular UI. All server requests belonging to a particular UI class are processed by the VaadinServlet or VaadinPortlet class. When a new client connects, it creates a new user session, represented by an instance of VaadinSession. Sessions are tracked using cookies stored in the browser.

You can obtain the VaadinSession of a UI with getSession() or globally with VaadinSession.getCurrent(). It also provides access to the lower-level session objects, HttpSession and PortletSession, through a WrappedSession. You can also access the deployment configuration through VaadinSession, as described in “Deployment Configuration”.

A session ends after the last UI instance expires or is closed, as described later.

Handling Session Initialization and Destruction

You can handle session initialization and destruction by implementing a SessionInitListener or SessionDestroyListener, respectively, to the VaadinService. You can do that best by extending VaadinServlet and overriding the servletInitialized() method, as outlined in Vaadin Servlet, Portlet, and Service.

Java

  1. public class MyServlet extends VaadinServlet
  2. implements SessionInitListener, SessionDestroyListener {
  3. @Override
  4. protected void servletInitialized() throws ServletException {
  5. super.servletInitialized();
  6. getService().addSessionInitListener(this);
  7. getService().addSessionDestroyListener(this);
  8. }
  9. @Override
  10. public void sessionInit(SessionInitEvent event)
  11. throws ServiceException {
  12. // Do session start stuff here
  13. }
  14. @Override
  15. public void sessionDestroy(SessionDestroyEvent event) {
  16. // Do session end stuff here
  17. }
  18. }

If using Servlet 2.4, you need to configure the custom servlet class in the servlet-class parameter in the web.xml descriptor instead of the VaadinServlet, as described in “Using a web.xml Deployment Descriptor”.

Loading a UI

When a browser first accesses a URL mapped to the servlet of a particular UI class, the Vaadin servlet generates a loader page. The page loads the client-side engine (widget set), which in turn loads the UI in a separate request to the Vaadin servlet.

A UI instance is created when the client-side engine makes its first request. The servlet creates the UIs using a UIProvider registered in the VaadinSession instance. A session has at least a DefaultUIProvider for managing UIs opened by the user. If the application lets the user open popup windows with a BrowserWindowOpener, each of them has a dedicated special UI provider.

Once a new UI is created, its init() method is called. The method gets the request as a VaadinRequest.

Customizing the Loader Page

The HTML content of the loader page is generated as an HTML DOM object, which can be customized by implementing a BootstrapListener that modifies the DOM object. To do so, you need to extend the VaadinServlet and add a SessionInitListener to the service object, as outlined in User Session. You can then add the bootstrap listener to a session with addBootstrapListener() when the session is initialized.

Loading the widget set is handled in the loader page with functions defined in a separate vaadinBootstrap.js script.

You can also use entirely custom loader code, such as in a static HTML page, as described in “Embedding UIs in Web Pages”.

Custom UI Providers

You can create UI objects dynamically according to their request parameters, such as the URL path, by defining a custom UIProvider. You need to add custom UI providers to the session object which calls them. The providers are chained so that they are requested starting from the one added last, until one returns a UI (otherwise they return null). You can add a UI provider to a session most conveniently by implementing a custom servlet and adding the UI provider to sessions in a SessionInitListener.

You can find an example of custom UI providers in “Providing a Fallback UI”.

Preserving UI on Refresh

Reloading a page in the browser normally spawns a new UI instance and the old UI is left hanging, until cleaned up after a while. This can be undesired as it resets the UI state for the user. To preserve the UI, you can use the @PreserveOnRefresh annotation for the UI class. You can also use a UIProvider with a custom implementation of isUiPreserved().

Java

  1. @PreserveOnRefresh
  2. public class MyUI extends UI {

Adding the ?restartApplication parameter in the URL tells the Vaadin servlet to create a new UI instance when loading the page, thereby overriding the @PreserveOnRefresh. This is often necessary when developing such a UI in Eclipse, when you need to restart it after redeploying, because Eclipse likes to persist the application state between redeployments. If you also include a URI fragment, the parameter should be given before the fragment.

UI Expiration

UI instances are cleaned up if no communication is received from them after some time. If no other server requests are made, the client-side sends keep-alive heartbeat requests. A UI is kept alive for as long as requests or heartbeats are received from it. It expires if three consecutive heartbeats are missed.

The heartbeats occur at an interval of 5 minutes, which can be changed with the heartbeatInterval parameter of the servlet. You can configure the parameter in @VaadinServletConfiguration or in web.xml as described in “Other Servlet Configuration Parameters”.

When the UI cleanup happens, a DetachEvent is sent to all DetachListener#s added to the UI. When the [classname]#UI is detached from the session, detach() is called for it.

Closing UIs Explicitly

You can explicitly close a UI with close(). The method marks the UI to be detached from the session after processing the current request. Therefore, the method does not invalidate the UI instance immediately and the response is sent as usual.

Detaching a UI does not close the page or browser window in which the UI is running and further server request will cause error. Typically, you either want to close the window, reload it, or redirect it to another URL. If the page is a regular browser window or tab, browsers generally do not allow closing them programmatically, but redirection is possible. You can redirect the window to another URL with setLocation(), as is done in the examples in Closing a Session. You can close popup windows by making JavaScript close() call for them, as described in “Closing Popup Windows”.

If you close other UI than the one associated with the current request, they will not be detached at the end of the current request, but after next request from the particular UI. You can make that occur quicker by making the UI heartbeat faster or immediately by using server push.

Session Expiration

A session is kept alive by server requests caused by user interaction with the application as well as the heartbeat monitoring of the UIs. Once all UIs have expired, the session still remains. It is cleaned up from the server when the session timeout configured in the web application expires.

If there are active UIs in an application, their heartbeat keeps the session alive indefinitely. You may want to have the sessions timeout if the user is inactive long enough, which is the original purpose of the session timeout setting. If the closeIdleSessions parameter of the servlet is set to true in the web.xml, as described in “Using a web.xml Deployment Descriptor”, the session and all of its UIs are closed when the timeout specified by the session-timeout parameter of the servlet expires after the last non-heartbeat request. Once the session is gone, the browser will show an Out Of Sync error on the next server request. To avoid the ugly message, you may want to set a redirect URL for the UIs

, as described in “Customizing System Messages” .

The related configuration parameters are described in “Other Servlet Configuration Parameters”.

You can handle session expiration on the server-side with a SessionDestroyListener, as described in User Session.

Closing a Session

You can close a session by calling close() on the VaadinSession. It is typically used when logging a user out and the session and all the UIs belonging to the session should be closed. The session is closed immediately and any objects related to it are not available after calling the method.

When closing the session from a UI, you typically want to redirect the user to another URL. You can do the redirect using the setLocation() method in Page. This needs to be done before closing the session, as the UI or page are not available after that. In the following example, we display a logout button, which closes the user session.

Java

  1. public class MyUI extends UI {
  2. @Override
  3. protected void init(VaadinRequest request) {
  4. setContent(new Button("Logout", event -> {// Java 8
  5. // Redirect this page immediately
  6. getPage().setLocation("/myapp/logout.html");
  7. // Close the session
  8. getSession().close();
  9. }));
  10. // Notice quickly if other UIs are closed
  11. setPollInterval(3000);
  12. }
  13. }

See the on-line example.

This is not enough. When a session is closed from one UI, any other UIs attached to it are left hanging. When the client-side engine notices that a UI and the session are gone on the server-side, it displays a “Session Expired” message and, by default, reloads the UI when the message is clicked. You can customize the message and the redirect URL in the system messages

, as described in “Customizing System Messages” .

The client-side engine notices the expiration when user interaction causes a server request to be made or when the keep-alive heartbeat occurs. To make the UIs detect the situation faster, you need to make the heart beat faster, as was done in the example above. You can also use server push to close the other UIs immediately, as is done in the following example. Access to the UIs must be synchronized as described in “Server Push”.

Java

  1. @Push
  2. public class MyPushyUI extends UI {
  3. @Override
  4. protected void init(VaadinRequest request) {
  5. setContent(new Button("Logout", event -> {// Java 8
  6. for (UI ui: VaadinSession.getCurrent().getUIs())
  7. ui.access(() -> {
  8. // Redirect from the page
  9. ui.getPage().setLocation("/logout.html");
  10. });
  11. getSession().close();
  12. }));
  13. }
  14. }

See the on-line example.

In the above example, we assume that all UIs in the session have push enabled and that they should be redirected; popups you might want to close instead of redirecting. It is not necessary to call close() for them individually, as we close the entire session afterwards.