Track Active Sessions with HttpSessionListener Example Use Case

This example explains how to use a HttpSessionListener in a web application. The purpose of this interface is to track active sessions in a web application. The HttpSessionListener 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.

HttpSessionListener receives notifications for active sessions

In order to listen to session changes we need to implement the javax.servlet.HttpSessionListener interface. this interface lets us listen to the following events, the names speak for themselves.

  • sessionCreated()
  • sessionDestroyed()

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.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class SessionListener implements HttpSessionListener {

    private static int activeSessions;

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        activeSessions++;
        System.out.println("session created - total active sessions: " + activeSessions);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        activeSessions--;
        System.out.println("session destroyed - total active sessions: " + activeSessions);
    }
}
Warning: counting sessions will only count sessions of the current Web Application.

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.SessionListener</listener-class>
    </listener>
    
</web-app>

How does it work

When a session is created the sessionCreated() event is raised. When a session is destroyed the sessionDestroyed() event is raised.

References

You may also like...