Showing posts with label ServletContextListener. Show all posts
Showing posts with label ServletContextListener. Show all posts

Saturday, 21 June 2014

Servlets Listeners

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 Are Servlet Listeners?

In Java web applications, a Servlet Listener is a special Java class designed to monitor and respond to lifecycle events and state changes occurring in the web container. Built on the classic Observer design pattern, listeners automatically run custom code when specific events occur.

Instead of manually polling or handling setup logic inside servlets, listeners allow you to automatically execute initialization routines, clean up system resources, track active user sessions, or react whenever attributes are added, updated, or removed across different servlet scopes.

Major Types of Servlet Listeners

Servlet listeners in Java EE / Jakarta EE are broadly divided into three main categories based on the scope they monitor:

  • ServletContext Listeners: Monitor application-wide lifecycle events and attributes.
    Examples: ServletContextListener (monitors startup and shutdown) and ServletContextAttributeListener (tracks context attribute changes).
  • HttpSession Listeners: Track user session creation, expiration, and attribute management.
    Examples: HttpSessionListener (tracks active sessions/logged-in users) and HttpSessionAttributeListener (detects session data modifications).
  • ServletRequest Listeners: Intercept individual client HTTP request lifecycles.
    Examples: ServletRequestListener (runs code on request creation/destruction) and ServletRequestAttributeListener.

Why Use Servlet Listeners?

  • Application Startup & Teardown: Ideal for initializing shared database connection pools or background tasks when the web app starts, and safely releasing them on shutdown.
  • Session Tracking & Analytics: Track the total count of active sessions or concurrent users logged into the platform in real time.
  • Loose Coupling: Decouple event-driven logic and monitoring tasks completely from your core business servlets.
  • Simple Configuration: Easily configure listeners in web.xml using the <listener> tag or by annotating the class with @WebListener.

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=7NtVn1_TSAg

Click the below Image to Enlarge
Servlets Listeners
Servlets Listeners
See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • 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
  • Servlets : ServletContextListener Introduction

    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

    Introduction to ServletContextListener

    In Java web applications, managing global lifecycle events is crucial for executing startup initializations and shutdown cleanup routines. The ServletContextListener interface (from the javax.servlet package) provides a clean callback mechanism that notifies your web application when the servlet context is initialized or destroyed.

    The web container triggers these lifecycle events when the application is first deployed and ready to process requests, and again when the application is undeployed or the server shuts down. This makes ServletContextListener the primary choice for initializing shared resources such as database connection pools, global configurations, and application caches.

    Core Lifecycle Methods

    The ServletContextListener interface defines two foundational lifecycle callback methods:

    • contextInitialized(ServletContextEvent sce): Executed when the servlet context is initialized. Use this hook to load startup parameters, prepare logging frameworks, or bind application-wide objects into ServletContext.
    • contextDestroyed(ServletContextEvent sce): Executed when the servlet context is shutting down. Use this hook to close active database connections, shut down background executor services, and clean up shared system resources.
    @WebListener
    public class AppInitListener implements ServletContextListener {

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

        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            System.out.println("ServletContext destroyed. Releasing global resources.");
        }
    }

    Why Use ServletContextListener?

    • Guaranteed Pre-Execution: Runs before any servlets, filters, or client requests are handled by the web container.
    • Graceful Teardown: Safeguards your application from connection leaks and thread locks during server shutdown or redeployments.
    • Shared Application Scope: Enables seamless configuration and object sharing across all servlets via the global ServletContext.

    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=K74XxH3-wZU

    Click the below Image to Enlarge
    ServletContextListener 
    ServletContextListener 
    ServletContextListener 
    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Tutorials