How to Be Notified about Events (Listeners)
The Servlet API provides a number of listener interfaces that you can implement to be notified about various events. You only need to implement the interface in a class and declare that class as listener in the web.xml deployment descriptor.
The Servlet API defines the following listener interfaces for applications:
| Interface | Events |
|---|---|
| ServletContextListener | Initialization and destruction of the application |
| ServletContextAttributeListener | Changes in context attributes |
| ServletRequestListener | Creation and destruction of requests |
| ServletRequestAttributeListener | Changes in request attributes |
| HttpSessionListener | Creation and destruction of sessions |
| HttpSessionAttributeListener | Changes in session attributes |
Note that the interfaces HttpSessionActivationListener and HttpSessionBindingListener are not listener interfaces to be implemented at the application level, but are implemented by objects being bound to a session.
The following web.xml snippet shows how to declare a listener (any listener - it does not matter which interface(s) it implements):
<listener> <listener-class>com.jarfiller.example.SessionLogger</listener-class> </listener>
This is an example shows the implementation of a simple listener:
import javax.servlet.http.*;
public class SessionLogger implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
event.getSession().getServletContext().log("Created new session");
}
public void sessionDestroyed(HttpSessionEvent event) {
event.getSession().getServletContext().log("Session will be destroyed");
}
}

