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>
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023