![]() |
![]() |
||||
A session listener receives notifications when a session is created or destroyed.
This is useful for logging, or to maintain a list of all active sessions.
This is also useful when writing a distributable web application, to ensure that session replication to other members of the cluster is working as expected.
If you also want to hear about changes to sessions, see Session Attribute Listener. Both of these interfaces can be implemented in the same class, to create a listener which is notified about create, destroy and change events.
This page focuses only on the Session Listener interface.
To create a Session Listener, create a class which implements the HttpSessionListener interface.
This involves implementation of the following two methods:
public void sessionCreated(HttpSessionEvent sessionEvent);
|
This method is called whenever a session is created.
This method is called whenever a session is being invalidated (eg: due to a session timeout).
The session is passed to both of the above methods in the HttpSessionEvent object.
It can be retrieved as follows:
HttpSession session = sessionEvent.getSession();
|
import javax.servlet.*;
|
Add the above class to WEB-INF/classes, and add the following in web.xml to activate our new SessionListener.
<listener> <listener-class>MySessionListener</listener-class> </listener>
Note that the above class was not put in a package, so no package name is specified in the <listener-class> tag.