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;

public class SessionListener implements HttpSessionListener {

    private static int activeSessions;

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

    public void sessionDestroyed(HttpSessionEvent event) {
        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=""
                   " version="3.1">


How does it work

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


You may also like...