Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Example of ServletContextListener Interface in Servlet

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 398
    Comment on it

    ServletContextListener Interface : In almost every web application there is a common scenario that application should need some pre-initialized data before starting the application. There are some actions which we need to perform before application started or deploying the application like running database scripts, creating database tables, initialize database connection and initialize logging etc.

    To do this you need to implement the ServletContextListener interface. This interface provides the two methods which we need to implement. The ServletContextListener interface has following methods :

    1. public void contextInitialized(ServletContextEvent e): is called when application is first deployed on the web server.
    2. public void contextDestroyed(ServletContextEvent e): is called when application is destroyed or undeployed from the web server.

    Only those two methods are used to handle the events occured at time of deployment and undeployment of application. Here you can see one more class is used called ServletContextEvent. ServletContextEvent has only one constructor

    ServletContextEvent(ServletContext e)
    

    and the instance of ServletContextEvent class is created by web container. ServletContextEvent has only one method which gives the instance of servlet context : public ServletContext getServletContext(): this will returns the ServletContext instance.

    Example of ServletContextListener interface : Following is the example of ServletContextListener interface and ServletContextEvent class. Here we are going to initialize the logging object at the time of container starts which will be used to error logging.

    Container initialize the log4j object at the time of application deployment.

    ContextListener.java

    package org.test.listener;
    
    import java.io.File;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import org.apache.log4j.PropertyConfigurator;
    
    @WebListener("application context listener")
    public class ContextListener implements ServletContextListener {
    
        /**
         * Initialize log4j when the application is being started
         */
        @Override
        public void contextInitialized(ServletContextEvent event) {
            // initialize log4j here
            ServletContext context = event.getServletContext();
            String log4jConfigFile = context.getInitParameter("log4j-config-location");
            String fullPath = context.getRealPath("") + File.separator + log4jConfigFile;
            //System.out.println(System.getProperty("java.class.path"));
            PropertyConfigurator.configure(fullPath);
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent event) {
            // do nothing
        }  
    }
    

    log4j.properties

    #log4j configuration
    log4j.rootLogger=DEBUG, fileappender
    
    log4j.appender.fileappender=org.apache.log4j.FileAppender
    log4j.appender.fileappender.File=app/logs/Application.log
    log4j.appender.fileappender.MaxFileSize=500KB
    
    ## Keep one backup file
    log4j.appender.fileappender.MaxBackupIndex=3
    log4j.appender.fileappender.layout=org.apache.log4j.PatternLayout
    log4j.appender.fileappender.layout.ConversionPattern=[%c] [%d{dd MMM yyyy - hh:mm:ss}] %5p - %m %n
    

    Last you need to do the entry of the listener in the web.xml

    <web-app>
    <context-param>
     <param-name>log4j-config-location</param-name>
     <param-value>WEB-INF/log4j.properties</param-value>
    </context-param>
    <listener>
           <listener-class>org.test.listener.ContextListener </listener-class>
    </listener>
    </web-app>
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: