[ Team LiB ] Previous Section Next Section

Recipe 11.9 Using a Listener to Track the Session Lifecycle


You want an object that implements the HttpSessionListener interface to respond when a session is created or destroyed.


Create a listener class that implements the HttpSessionListener interface, and register the class in your deployment descriptor.


The servlet API provides the javax.servlet.http.HttpSessionListener interface for use in responding to session creation or destruction. A class that implements this interface can perform custom behavior on either (or both) of these two events. Here is the process for creating and declaring a session listener for your web application:

  1. Create a class that implements the HttpSessionListener interface. This interface defines two methods: sessionCreated( ) and sessionDestroyed( ), each of which accept a single HttpSessionEvent parameter.

  2. Make sure the implementing class has a zero-argument constructor.

  3. Place the compiled class in the WEB-INF/classes directory of your web application (including any of its package-related directories); or store the class in a JAR located in the WEB-INF/lib directory.

  4. Declare the listener in the web.xml deployment descriptor.

  5. Restart the web container (if necessary), which will instantiate your listener class and register it as a listener for all new sessions and session invalidations in the web application.

Objects that are bound to sessions should implement the HttpSessionBindingListener interface. This listener does not have to be configured in the deployment descriptor, but the bound objects must implement HttpSessionBindingListener, as well as the valueBound( ), valueUnbound( ), and init( ) methods. The HttpSessionActivationListener is designed for sessions that migrate between Java Virtual Machines (JVMs). Objects that are bound to these sessions must implement HttpSessionActivationListener and its two methods: sessionDidActivate( ) and sessionWillActivate( ).

Here is the web.xml entry for our example listener class:


The HttpSessionListener class in Example 11-15 keeps a count of live sessions in the web application and writes a message to the console whenever a session is created or destroyed. It would be better to log messages using a component such as log4j, which I'll discuss in Chapter 14.

Example 11-15. Keeping track of session activity with a listener class
package com.jspservletcookbook;

import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionListen implements HttpSessionListener {
    private int sessionCount;

    public SessionListen( ) {
        this.sessionCount = 0;
    public void sessionCreated(HttpSessionEvent se){

        HttpSession session = se.getSession( );


        //increment the session count

        String id = session.getId( );

        Date now = new Date( );

        String message = new StringBuffer(
          "New Session created on ").
            append(now.toString( )).append("\nID: ").
              append(id).append("\n").append("There are now ").
                  " live sessions in the application."). toString( );
    public void sessionDestroyed(HttpSessionEvent se){
        HttpSession session = se.getSession( );

        String id = session.getId( );

        --sessionCount;//decrement the session count variable

        String message = new StringBuffer("Session destroyed" + 
          "\nValue of destroyed session ID is").
                "There are now ").append(""+sessionCount).append(
                  " live sessions in the application.").toString( );


Each listener must have a zero-argument constructor. The SessionListen class has one instance variable, an int that keeps track of the number of sessions. In the sessionCreated( ) method, the code gets access to the new session by calling the HttpSessionEvent.getSession( ) method. The session's timeout is then reset to 60 seconds, so the creating and destroying can be observed in the console without a lot of delay.

An HttpSessionListener class is notified only of requests to pages that create new sessions, such as with the request.getSession( ) method. This listener is also notified if a servlet or JSP invalidates an existing session, an event that will trigger the class's sessionDestroyed( ) method. If a servlet or JSP is accessed, but does not do session tracking, then the listener is not notified of those activities; the same is true when the session is further accessed through the web application after it is created, unless it is explicitly invalidated.

Similar messaging and access to the HttpSession object takes place in the sessionDestroyed( ) method. The resulting console in Figure 11-6 shows that you can get information about the HttpSession object in both of the listener's methods.

Figure 11-6. Notifications of session creation and invalidation

Using the HttpSessionListener interface, it is possible to create classes that monitor how many sessions are created during a certain period of time, and how long it takes before they are left idle and timeout.

See Also

Chapter 14 on using listeners to log messages; Recipe 11.4 on checking the validity of a session; Chapter 1 on web.xml; Chapter 7 of the Servlet v2.3 and 2.4 specifications on sessions; the javax.servlet.http.HttpSession API at http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpSession.html.

    [ Team LiB ] Previous Section Next Section