@WebListener
This section contains detailed description of @WebListener annotation and its implementation with sample code.
Servlet listeners are added in the Servlet 2.3. The main task of the listener is to listen the particular events and process your own task on that event. For example, if you want to initialize a database connection before your application starts, ServletContextListener will be implemented to do that. Another good example is -when you want to do some task on the creation and destruction of a session. For this purpose you need to implement HttpSessionListener.
Prior to Servlet 3.0, you need to register filter using deployment descriptor(web.xml). You can do this as follows :
<listener> <listener-class>roseindia.MyServletContextListener</listener-class> </listener>
Now(after introduction of Servlet 3.0), you can do this using @WebListener annotation(see the below example). You don't need to configure in deployment descriptor(web.xml).
Using @WebListener annotation following type of listeners can be register :
- Context Listener (javax.servlet.ServletContextListener)
- Context Attribute Listener
(javax.servlet.ServletContextAttributeListener)
- Servlet Request Listener (javax.servlet.ServletRequestListener)
- Servlet Request Attribute Listener
(javax.servlet.ServletRequestAttributeListener)
- Http Session Listener (javax.servlet.http.HttpSessionListener)
- Http Session Attribute Listener (javax.servlet.http.HttpSessionAttributeListener)
The tools and technology used in the example is given below :
- Eclipse Helios 3.6.1
- Tomcat 7
- jdk1.6.0_18
EXAMPLE
In the given below example, we are going to register ServletContextListener using @WebListener annotation as follows :
package roseindia; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; @WebListener public class WebListenerAnnotation implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent arg0) { System.out.println("ServletContextListener destroyed"); } @Override public void contextInitialized(ServletContextEvent arg0) { System.out.println("ServletContextListener started"); } }
OUTPUT
When you execute your application, you will get the following message on console :