August 28, 2011

ServletContextListener Event Handler Implementation

The ServletContextListener interface is part of the Servlet API and lets us create an event-handler class that listens to events on the ServletContext object, namely, the ServletContext object creation/initialization and the ServletContext object destruction.

The ServletContextEvent object that is passed as an argument to the 2 listener methods provides a handle to the ServletContext object in order to set any attributes.

1) Create a class that implements the ServletContextListener interface methods, contextInitialized () and contextDestroyed()

package info.icontraining.servlets.listeners;

import javax.servlet.*;

public class MyServletContextListener implements ServletContextListener {
   public void contextInitialized(ServletContextEvent sce) {
      System.out.println("Servlet Context created");

      // code to acquire resource, to set as 
      // attr in application scope

      ServletContext sc = sce.getServletContext();
      sc.setAttribute("attr-name", "attr-value");
   }

   public void contextDestroyed(ServletContextEvent sce) {
      // any clean-up code
      System.out.println("Servlet Context destroyed");
   }
}

2) Configure the listener in the web.xml deployment descriptor,

<listener>
   <listener-class>    
      info.icontraining.servlets.listeners.MyServletContextListener
   </listener-class>
</listener>

3) Deploy the application to the Application Server/ Web Container and check in the server/console log for the following output,

INFO  [STDOUT] Servlet Context created

No comments:

Post a Comment