Friday 13 June 2014

Servlets : ServletContextListener Demo


















Click here to watch in Youtube : https://www.youtube.com/watch?v=XS4QcA6xmQc

Click the below Image to Enlarge

ServletContextListenerDemo Project Dir Structure

MyServletContextListener.java
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyServletContextListener implements ServletContextListener
{

    @Override
    public void contextInitialized( ServletContextEvent servletContextEvent )
    {
        System.out.println("\n###################################\n");

        System.out.println("contextInitialized method has been called in "
                + this.getClass().getName());

        ServletContext servletContext = servletContextEvent.getServletContext();

        System.out.println(servletContext + " is Initialized or Created");

        System.out.println("\n#####################################\n");

        /*
         * If ServletContext is created, based on that if you want to perform
         * any operation then you can do it here.
         */

    }

    @Override
    public void contextDestroyed( ServletContextEvent servletContextEvent )
    {
        System.out.println("\n###################################\n");

        System.out.println("contextDestroyed method has been called in "
                + this.getClass().getName());

        ServletContext servletContext = servletContextEvent.getServletContext();

        System.out.println(servletContext + " is destroyed");

        System.out.println("\n#####################################\n");

        /*
         * If ServletContext is Destroyed, based on that if you want to perform
         * any operation then you can do it here.
         */

    }

}

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    metadata-complete="true" version="3.0">
    
    <display-name>ServletContextListenerDemo</display-name>
    <description>
        This is a simple web application with a source code organization
        based on the recommendations of the Application Developer's Guide.
    </description>
    
        
    <listener>
        <listener-class>MyServletContextListener</listener-class>
    </listener>
    
</web-app>

Environment Used 

JDK version :1.7.0_51
Tomcat version : 7.0.50 

To Download ServletContextListenerDemoApp Project Click the below link

https://sites.google.com/site/javaee4321/servlets/ServletContextListenerDemoApp.zip?attredirects=0&d=1

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • No comments:

    Post a Comment