Java.Servlets.Listeners

🎯 Why Use Listeners?

They let you hook into the lifecycle of:

  • The ServletContext (entire app)
  • HttpSession (per user)
  • ServletRequest (per request)

You use them to:

  • Initialize or clean up resources (e.g. DB pools)
  • Log application or session events
  • Track user sessions
  • Inject defaults or track attribute changes
  • Implement analytics or custom metrics

🔧 Types of Listeners (Servlet API)

Listener InterfaceListens ToWhen to Use
ServletContextListenerApp start and stopInitialize app-wide resources (e.g. DB, caches)
HttpSessionListenerSession create/destroyTrack logged-in users, cleanup session data
ServletRequestListenerRequest start/endLogging, timing, diagnostics
ServletContextAttributeListenerAttribute added/removed in contextGlobal config changes or plugin loading
HttpSessionAttributeListenerSession attribute changeTrack login/logout events, cart changes, etc.
ServletRequestAttributeListenerRequest attribute changeFor internal middleware logic (rarely used directly)

🧪 Example: Tracking Active Sessions

@WebListener
public class SessionCounterListener implements HttpSessionListener {

    private static int activeSessions = 0;

    public void sessionCreated(HttpSessionEvent se) {
        activeSessions++;
        System.out.println("Session created. Active sessions: " + activeSessions);
    }

    public void sessionDestroyed(HttpSessionEvent se) {
        activeSessions--;
        System.out.println("Session destroyed. Active sessions: " + activeSessions);
    }
}

🚀 Example: Initializing Resources on App Startup

@WebListener
public class AppStartupListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("App started");
        // Initialize DB connection, load config, etc.
    }

    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("App shutting down");
        // Cleanup resources
    }
}

🛠️ Registering Listeners

1. Using Annotations:

@WebListener
public class MyListener implements HttpSessionListener { ... }

2. Using web.xml:

<listener>
  <listener-class>com.myapp.MyListener</listener-class>
</listener>

✅ Summary

Listener TypeBest For
ServletContextListenerApp-level setup & teardown
HttpSessionListenerTracking sessions, auth, cleanup
ServletRequestListenerRequest-level timing/logging
AttributeListenersReacting to changes in session/context/request
This entry was posted in Без рубрики. Bookmark the permalink.