Tutorials Logic, IN info@tutorialslogic.com

Servlet Listeners ServletContextListener, HttpSessionListener: Tutorial, Examples, FAQs & Interview Tips

Servlet Listeners ServletContextListener, HttpSessionListener

Servlet Listeners ServletContextListener, HttpSessionListener is an important Servlet topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.

For this page, focus on what problem Servlet Listeners ServletContextListener, HttpSessionListener solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .

A strong understanding of Servlet Listeners ServletContextListener, HttpSessionListener should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.

Servlet Listeners ServletContextListener HttpSessionListener should be studied as a practical Servlet lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the servlet > listeners page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

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 Interface Events Use Case
ServletContextListener contextInitialized, contextDestroyed App startup/shutdown tasks
ServletContextAttributeListener attributeAdded, attributeRemoved, attributeReplaced Monitor app-scope attributes
HttpSessionListener sessionCreated, sessionDestroyed Track active sessions
HttpSessionAttributeListener attributeAdded, attributeRemoved, attributeReplaced Monitor session attributes
ServletRequestListener requestInitialized, requestDestroyed Request logging, timing
HttpSessionBindingListener valueBound, valueUnbound Object notified when added to session

ServletContextListener - App Startup/Shutdown

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

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();
    }
}

HttpSessionListener and ServletRequestListener

HttpSessionListener and ServletRequestListener
@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");
        }
    }
}

Detailed Learning Notes for Servlet Listeners ServletContextListener, HttpSessionListener

When studying Servlet Listeners ServletContextListener, HttpSessionListener, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.

In Servlet, Servlet Listeners ServletContextListener, HttpSessionListener becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.

  • Identify the main problem this topic solves.
  • Write the smallest possible working example.
  • Change one input or option and observe the result.
  • Note the mistake that would break the example.

Servlet Listeners ServletContextListener HttpSessionListener Java review example

Servlet Listeners ServletContextListener HttpSessionListener Java review example
class ServletListenersServletContextListenerHttpSessionListenerReview {
    public static void main(String[] args) {
        String state = "ready";
        System.out.println("Servlet Listeners ServletContextListener HttpSessionListener: " + state);
    }
}

Servlet Listeners ServletContextListener HttpSessionListener guard example

Servlet Listeners ServletContextListener HttpSessionListener guard example
String value = null;
if (value == null) {
    System.out.println("Servlet Listeners ServletContextListener HttpSessionListener: handle the missing value before continuing");
}
Key Takeaways
  • Explain the purpose of Servlet Listeners ServletContextListener, HttpSessionListener before memorizing syntax.
  • Run or trace one small Servlet example and confirm the output.
  • Test one normal case, one edge case, and one mistake case for Servlet Listeners ServletContextListener, HttpSessionListener.
  • Write the rule in your own words after checking the example.
  • Connect Servlet Listeners ServletContextListener, HttpSessionListener to a real project scenario instead of treating it as an isolated definition.
Common Mistakes to Avoid
WRONG Memorizing Servlet Listeners ServletContextListener HttpSessionListener without the situation where it is useful.
RIGHT Connect Servlet Listeners ServletContextListener HttpSessionListener to a concrete Servlet task.
Purpose makes syntax easier to recall.
WRONG Testing Servlet Listeners ServletContextListener HttpSessionListener only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Changing code before reading the visible symptom or error message.
RIGHT Inspect the output, state, configuration, or stack trace connected to Servlet Listeners ServletContextListener HttpSessionListener.
Evidence keeps debugging focused.
WRONG Memorizing Servlet Listeners ServletContextListener HttpSessionListener without the situation where it is useful.
RIGHT Connect Servlet Listeners ServletContextListener HttpSessionListener to a concrete Servlet task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it handles a different input or condition.
  • Write one mistake related to Servlet Listeners ServletContextListener, HttpSessionListener, then fix it and explain the fix.
  • Summarize when to use Servlet Listeners ServletContextListener, HttpSessionListener and when another approach is better.
  • Write a small example that uses Servlet Listeners ServletContextListener HttpSessionListener in a realistic Servlet scenario.
  • Change one important value in the Servlet Listeners ServletContextListener HttpSessionListener example and predict the result first.

Frequently Asked Questions

The common mistake is memorizing syntax without understanding when the behavior changes or fails.

Remember the problem it solves in Servlet, then attach the syntax or steps to that problem.

You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.

They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.

Ready to Level Up Your Skills?

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