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.*;

public class SessionIdLogger implements HttpSessionIdListener {

    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=""
                   " version="3.1">


How does it work

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


You may also like...