Servlet Listeners :-


Web Listeners are used for listening to events in the life cycle of web applications. Listeners gets triggered automatically when an event occurs. Example of events includes -

  • Request came in and going out of scope of web application.
  • Session created or destroyed.
  • Attribute added, removed or replaced in session, application and request.
There are commonly following types of web listeners used -

Listener Interface Listener Interface Methods Event Class Description
1-ServletRequestListener requestInitialized()
requestDestroyed()
ServletRequestEvent This interface gets notified each time request came in or going out of scope of application.
2-ServletAttributeRequestListener attributeAdded()
attributeRemoved()
attributeReplaced()
ServletRequestAttributeEvent This interface gets notified each time an attribute added, removed or replaced from request.
3-HttpSessionListener sessionCreated()
sessionDestroyed()
HttpSessionEvent This interface gets notified each time a session created or destroyed.
4-HttpSessionAttributeListener attributeAdded()
attributeRemoved()
attributeReplaced()
HttpSessionBindingEvent This interface gets notified each time an attribute added, removed or replaced from session.
5-ServletContextListener contextInitialized()
contextDestroyed()
ServletContextEvent This interface gets notified when servlet context created or destroyed.
6-ServletContextAttributeListener attributeAdded()
attributeRemoved()
attributeReplaced()
HttpSessionBindingEvent This interface gets notified each time an attribute added, removed or replaced from context(application).

Registring a Listener -

TO use a Listener, we need to register it. There are 2 ways to register a listener -

1- Using web.xml - We can register a listner in web.xml as follows -
 <listener>
        <listener-class>package_name.Class_Name</listener-class>
    </listener>        

2- WebListener Annotation - javax.servlet.annotation.WebListener annotation can also be used to register a class as listener. In that case we do not need to define it in web.xml. For Example -
@WebListener
public class MyListener implements ServletRequestListener
{
..........
.........
}