Tuesday, August 06, 2013

Listener - ServletContextListener Example

If You want to do something before application starts, then ServletContextListener is for you.

ServletContextListener is abstract interface provided as part of servler-api.jar which provides contextDestroyed and contextInitialized abstract method. One can create class which implements ServletContextListener and write implementation logic for example, logic that does something before web application starts.

AppContextListener Example :

package com.anuj.context;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * 
 * @author Anuj
 *
 */
public class AppContextListener implements ServletContextListener{

 @Override
 public void contextDestroyed(ServletContextEvent event) {
  System.out.println("TODO something on ServletContextListener Destroyed");
 }

 @Override
 public void contextInitialized(ServletContextEvent event) {
  System.out.println("TODO something on ServletContextListener Initialized");
 }

}

Defining AppContextListener in web.xml deployment descriptor :

    com.anuj.context.AppContextListener


Output :
INFO: Initializing ProtocolHandler ["ajp-apr-8009"]
Aug 06, 2013 10:03:16 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 960 ms
Aug 06, 2013 10:03:16 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Aug 06, 2013 10:03:16 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.27
TODO something on ServletContextListener Initialized
Aug 06, 2013 10:03:16 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-apr-8080"]
Aug 06, 2013 10:03:16 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-apr-8009"]
Aug 06, 2013 10:03:16 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 238 ms

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/