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 cofiguration example for our listener.

<listener>
    <listener-class>org.kodejava.example.servlet.MySessionListener</listener-class>
</listener>

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA. Support me by donating >> here <<.

Leave a Reply