How do I capture session creation and removal events?

Category: javax.servlet, viewed: 614 time(s).

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>
Bookmark this example!  

Most Viewed Examples

Google

100 Top & Latest


eXTReMe Tracker
visitor stats