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. The interface has two methods that we can implement, the sessionCreated(HttpSessionEvent event) and sessionDestroyed(HttpSessionEvent event) methods. To activate the listener we need to register it in the servlet container. To register the listener we can use the @WebListener annotation. Let’s see the full code snippet below.

package org.kodejava.servlet;

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

@WebListener
public class MySessionListener implements HttpSessionListener {

    // Notification that a new session was created
    @Override
    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
    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();

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

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

Wayan

Leave a Reply

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