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.
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 |
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());
}
}
}
@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");
}
}
}
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.
class ServletListenersServletContextListenerHttpSessionListenerReview {
public static void main(String[] args) {
String state = "ready";
System.out.println("Servlet Listeners ServletContextListener HttpSessionListener: " + state);
}
}
String value = null;
if (value == null) {
System.out.println("Servlet Listeners ServletContextListener HttpSessionListener: handle the missing value before continuing");
}
Memorizing Servlet Listeners ServletContextListener HttpSessionListener without the situation where it is useful.
Connect Servlet Listeners ServletContextListener HttpSessionListener to a concrete Servlet task.
Testing Servlet Listeners ServletContextListener HttpSessionListener only with the perfect input.
Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Changing code before reading the visible symptom or error message.
Inspect the output, state, configuration, or stack trace connected to Servlet Listeners ServletContextListener HttpSessionListener.
Memorizing Servlet Listeners ServletContextListener HttpSessionListener without the situation where it is useful.
Connect Servlet Listeners ServletContextListener HttpSessionListener to a concrete Servlet task.
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.
Explore 500+ free tutorials across 20+ languages and frameworks.