servlet listener example using eclipse

Servlet listener are the classes which listens to a particular type of events and when that event occurs , triggers the functionality. Such as when you create a session, or place an attribute in an session or if you passivate and activate in another container, to subscribe to these events you can configure listener in web.xml

eg. ServletContextListener
ServletContextAttributeListener
HttpSessionListener
HttpSessionAttributeListener
ServletRequestListener
ServletRequestAttributeListener
HttpSessionActivationListener
HttpSessionBindingListener

Servlet Listener Lifecycle?

 

Servlet Listener Lifecycle

Lifecycle listener modules provide a means of running short or long duration Java-based tasks within the application server environment, such as instantiation of singletons or RMI servers. These modules are automatically initiated at server startup and are notified at various phases of the server life cycle.

Servlet Listener order

If you want to execute listeners in a particular order, you should use deployment descriptor to define them.

Below statements are copied from Servlet Specification:

8.2.3:

If the order in which the listeners, servlets, filters are invoked is important to an application then a deployment descriptor must be used. When using annotations to define the listeners, servlets and filters, the order in which they are invoked is unspecified.

The ordering will be based on the order in which they are defined in the descriptor and on the absolute-ordering element in the web.xml or an ordering element in the web-fragment.xml.

Prior to this release of the specification (Java™ Servlet Specification, version 3), context listeners were invoked in random order. As of Servlet 3.0, the listeners are invoked in the order in which they are declared in the web.xml.

Implementations of javax.servlet.ServletContextListener are invoked at their contextInitialized method in the order in which they have been declared, and at their contextDestroyed method in reverse order.

Leave a Reply

Your email address will not be published. Required fields are marked *