Friday, 13 June 2014

Servlets : ServletContextListener Demo

Master Core Java & Servlets!

Subscribe to Ram N Java for beginner-friendly coding walkthroughs, web architecture lessons, and hands-on Java guides!

🔔 Subscribe to Ram N Java

What is ServletContextListener?

In Java web applications, the ServletContextListener interface (part of the javax.servlet package) provides a way to receive notifications about changes to the servlet context lifecycle. It allows developers to run startup initialization tasks when the web application is deployed, as well as teardown tasks when the application is shut down or undeployed.

Because it triggers before any filters or servlets are initialized, ServletContextListener is the standard mechanism for initializing application-wide resources such as database connection pools, loggers, caches, and global configuration settings.

Lifecycle Callback Methods

The ServletContextListener interface defines two essential lifecycle methods:

  • contextInitialized(ServletContextEvent sce): Executed when the web application is deployed and ready to process requests. This method is used to set application-level attributes and initialize heavy backend services.
  • contextDestroyed(ServletContextEvent sce): Executed when the servlet context is shutting down (e.g., during server shutdown or application redeployment). This is used to close database connections, release locks, and prevent memory leaks.
@WebListener
public class AppLifecycleListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        System.out.println("Web application initialized: " + context.getContextPath());
        context.setAttribute("appStatus", "Running");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("Web application stopped. Performing resource cleanup...");
    }
}

Key Advantages of Using ServletContextListener

  • Application Lifecycle Control: Guarantees that essential background resources and connections are initialized prior to serving client requests.
  • Safe Teardown & Cleanup: Helps avoid thread leaks and database connection hanging when an application is redeployed.
  • Global Scope Access: Attributes added to ServletContext during initialization become readily accessible to all servlets, JSPs, and filters.

Recommended Related Tutorials

Continue exploring servlet listeners and web architecture with these tutorials from Ram N Java:


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

    Tutorials