Metawerx Java Hosting Small Logo

Session Listener

A session listener receives notifications when a session is created or destroyed.

This is useful for logging, or to maintain a list of all active sessions.

This is also useful when writing a distributable web application, to ensure that session replication to other members of the cluster is working as expected.

If you also want to hear about changes to sessions, see Session Attribute Listener. Both of these interfaces can be implemented in the same class, to create a single listener which is notified about create, destroy and change events.

This page focuses only on the Session Listener interface.

Creating a SessionListener

To create a Session Listener, create a class which implements the HttpSessionListener interface.

This involves implementation of the following two methods:

public void sessionCreated(HttpSessionEvent sessionEvent);
public void sessionDestroyed(HttpSessionEvent sessionEvent);

Each listener class must also have a public constructor taking no arguments.

sessionCreated()

This method is called whenever a session is created.

sessionDestroyed()

This method is called whenever a session is being invalidated (eg: due to a session timeout).

HttpSession

The session is passed to both of the above methods in the HttpSessionEvent object.

It can be retrieved as follows:

HttpSession session = sessionEvent.getSession();

Full Example

import javax.servlet.*;

public final class MySessionListener
implements HttpSessionListener {

    public MySessionListener() {
    }

    public void sessionCreated(HttpSessionEvent sessionEvent) {

        // Get the session that was created
        HttpSession session = sessionEvent.getSession();

        // Store something in the session, and log a message
        try {
            System.out.println("[MySessionListener] Session created: "+session);
            session.setAttribute("foo""bar");
        catch (Exception e) {
            System.out.println("[MySessionListener] Error setting session attribute: " + e.getMessage());
        }
    }

    public void sessionDestroyed(HttpSessionEvent sessionEvent) {

        // Get the session that was invalidated
        HttpSession session = sessionEvent.getSession();

        // Log a message
        System.out.println("[MySessionListener] Session invalidated: "+session);
        System.out.println("[MySessionListener] Value of foo is: " + session.getAttribute("foo"));
    }
}

Adding the Session Listener to web.xml

Add the above class to WEB-INF/classes, and add the following in web.xml to activate our new SessionListener.

<listener>
    <listener-class>MySessionListener</listener-class>
</listener>

Note that the above class was not put in a package, so no package name is specified in the <listener-class> tag.

Other Listener Examples

navigation
metawerx specific
search
Share
tools
help

referring pages

Share