How do I capture session creation and removal events?

The Servlet specification define an HttpSessionListener interface that can be implemented if we want to listen to session creation and removal events.

package org.kodejava.example.servlet;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Date;

public class MySessionListener implements HttpSessionListener {

    // Notification that a new session was created
    public void sessionCreated(HttpSessionEvent event) {
        HttpSession session = event.getSession();

        System.out.println("New session created  : " + session.getId());
        System.out.println("Session creation time: " + new Date(session.getCreationTime()));

    // Notification that a session was invalidated
    public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();

        System.out.println("Session destroyed  : " + session.getId());

To make the listener works you need to configure in the the web.xml file. Below in a configuration example for our listener.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.