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
<!--https://search.maven.org/remotecontent?filepath=javax/servlet/javax.servlet-api/4.0.1/javax.servlet-api-4.0.1.jar-->
<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 convert Map to JSON and vice versa using Jackson? - June 12, 2022
- How do I find Java version? - March 21, 2022
- How do I convert CSV to JSON string using Jackson? - February 13, 2022