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 get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024