Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

Servlet Listeners

What are Servlet Listeners?

Servlet Listeners are event-driven components that respond to lifecycle events in the web application. They implement specific listener interfaces and are notified when events occur (application startup/shutdown, session creation/destruction, request creation/destruction).

Listener InterfaceEventsUse Case
ServletContextListenercontextInitialized, contextDestroyedApp startup/shutdown tasks
ServletContextAttributeListenerattributeAdded, attributeRemoved, attributeReplacedMonitor app-scope attributes
HttpSessionListenersessionCreated, sessionDestroyedTrack active sessions
HttpSessionAttributeListenerattributeAdded, attributeRemoved, attributeReplacedMonitor session attributes
ServletRequestListenerrequestInitialized, requestDestroyedRequest logging, timing
HttpSessionBindingListenervalueBound, valueUnboundObject notified when added to session
ServletContextListener - App Startup/Shutdown
package com.example.listeners;

import javax.servlet.*;
import javax.servlet.annotation.WebListener;
import java.sql.*;

@WebListener
public class AppContextListener implements ServletContextListener {

    private Connection dbConnection;

    // Called when the web application starts
    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext context = event.getServletContext();
        System.out.println("Application starting...");

        // Initialize shared resources
        try {
            // Initialize DB connection pool
            Class.forName("com.mysql.cj.jdbc.Driver");
            dbConnection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/mydb", "root", "password");

            // Store in application scope for all servlets to use
            context.setAttribute("dbConnection", dbConnection);
            context.setAttribute("appStartTime", System.currentTimeMillis());
            context.setAttribute("appVersion", "1.0.0");

            System.out.println("Database connection initialized");
        } catch (Exception e) {
            System.err.println("Failed to initialize DB: " + e.getMessage());
        }
    }

    // Called when the web application shuts down
    @Override
    public void contextDestroyed(ServletContextEvent event) {
        System.out.println("Application shutting down...");
        // Release resources
        try {
            if (dbConnection != null && !dbConnection.isClosed()) {
                dbConnection.close();
                System.out.println("Database connection closed");
            }
        } catch (SQLException e) {
            System.err.println("Error closing DB: " + e.getMessage());
        }
    }
}

HttpSessionListener and ServletRequestListener

Session and Request Listeners
@WebListener
public class SessionCountListener implements HttpSessionListener {

    // Thread-safe counter for active sessions
    private static java.util.concurrent.atomic.AtomicInteger activeSessions
            = new java.util.concurrent.atomic.AtomicInteger(0);

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        int count = activeSessions.incrementAndGet();
        System.out.println("Session created: " + event.getSession().getId()
                + " | Active sessions: " + count);
        // Store count in application scope
        event.getSession().getServletContext()
             .setAttribute("activeSessions", count);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        int count = activeSessions.decrementAndGet();
        System.out.println("Session destroyed: " + event.getSession().getId()
                + " | Active sessions: " + count);
        event.getSession().getServletContext()
             .setAttribute("activeSessions", count);
    }

    public static int getActiveSessions() {
        return activeSessions.get();
    }
}
@WebListener
public class RequestTimingListener implements ServletRequestListener {

    @Override
    public void requestInitialized(ServletRequestEvent event) {
        // Store start time in request attribute
        event.getServletRequest().setAttribute("startTime", System.currentTimeMillis());
    }

    @Override
    public void requestDestroyed(ServletRequestEvent event) {
        Long startTime = (Long) event.getServletRequest().getAttribute("startTime");
        if (startTime != null) {
            long duration = System.currentTimeMillis() - startTime;
            HttpServletRequest req = (HttpServletRequest) event.getServletRequest();
            System.out.println("Request to " + req.getRequestURI()
                    + " took " + duration + "ms");
        }
    }
}

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.