HttpSessionIdListener Example Use Case

This example explains how to use a HttpSessionIdListener in a web application. It’s an interface for receiving notification events about HttpSession id changes. The HttpSessionIdListener can be registerd by @WebListener annotation, adding the listener to the servlet descriptor or programmatically adding a listener with .addListener() to the servlet context. In this example we use the @WebListener annotation.

HttpSessionIdListener receives notifications for HttpSession id changes

In order to listen to a session id change, we need to implement the javax.servlet.HttpSessionIdListener interface. This interface lets us listen to the following event.

  • sessionIdChanged(): this event will be raised an HttpSession id has been changed.

To register a listener we can add the @WebListener, define the listener in the servlet descriptor (web.xml) or programatigally add it to the servlet context. In this example we choose to add the listener through the @WebListener annotation.

package com.memorynotfound;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;

@WebListener
public class SessionIdLogger implements HttpSessionIdListener {

    @Override
    public void sessionIdChanged(HttpSessionEvent event, String oldSessionId) {
        System.out.println("session id changed");
    }
    
}

Note: If you prefer the web.xml servlet descriptor over the @WebListener annotation you can add the context listener as follows:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">

    <listener>
        <listener-class>com.memorynotfound.SessionIdLogger</listener-class>
    </listener>
    
</web-app>

How does it work

When a session id has been changed the sessionIdChanged() event is raised.

References

You may also like...