java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.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 cofiguration example for our listener.

<listener>
    <listener-class>com.javacoderanch.example.servlet.MySessionListener</listener-class>
</listener>