Java.Servlet.Examples of listeners

🧠 Full List of Important Servlet Listeners + Examples

Listener InterfacePurposeExample Event It Catches
ServletContextListenerApp startup and shutdownServer starts your app, or app is undeployed
HttpSessionListenerSession creation and destructionUser opens a session (new visit) or session expires
ServletRequestListenerRequest creation and destructionEach new HTTP request starts or ends
ServletContextAttributeListenerAttribute added/removed/replaced in contextSomeone puts something into ServletContext
HttpSessionAttributeListenerAttribute added/removed/replaced in sessionUser sets attribute into session
ServletRequestAttributeListenerAttribute added/removed/replaced in requestDeveloper adds data into request object

🎯 Examples for Each Listener


1. ServletContextListener

✅ Do something when the application starts or shuts down.

@WebListener
public class AppStartupShutdownListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("App started at: " + new java.util.Date());
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("App is shutting down...");
    }
}

Use case:

  • Initialize DB connections at app start.
  • Clean up threads, close connections at app shutdown.

2. HttpSessionListener

✅ Track when user sessions are created or destroyed.

@WebListener
public class MySessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("New session created: " + se.getSession().getId());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("Session destroyed: " + se.getSession().getId());
    }
}

Use case:

  • Count online users.
  • Cleanup session-related resources.

3. ServletRequestListener

✅ Hook into each HTTP request lifecycle.

@WebListener
public class RequestListenerExample implements ServletRequestListener {
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        System.out.println("New request started at " + new java.util.Date());
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        System.out.println("Request finished.");
    }
}

Use case:

  • Start timing requests (for performance monitoring).
  • Set up default values for every request.

4. ServletContextAttributeListener

✅ Listen for attributes being added/removed/changed in the application scope.

@WebListener
public class AppAttributeListener implements ServletContextAttributeListener {
    @Override
    public void attributeAdded(ServletContextAttributeEvent event) {
        System.out.println("Attribute added: " + event.getName() + " = " + event.getValue());
    }
}

Use case:

  • Track global setting changes.
  • Audit what data is being put into ServletContext.

5. HttpSessionAttributeListener

✅ Listen for attributes being added/removed/changed inside a user session.

@WebListener
public class SessionAttributeLogger implements HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        System.out.println("Session attribute added: " + event.getName());
    }
}

Use case:

  • Track login/logout events stored in session.
  • Auto-update session statistics.

6. ServletRequestAttributeListener

✅ Watch attributes being added/removed/changed in individual requests.

@WebListener
public class RequestAttributeLogger implements ServletRequestAttributeListener {
    @Override
    public void attributeAdded(ServletRequestAttributeEvent event) {
        System.out.println("Request attribute added: " + event.getName() + " = " + event.getValue());
    }
}

Use case:

  • Debugging request data.
  • Auditing sensitive request changes.

🛠️ Quick Memory Table

EventListener
App starts or stopsServletContextListener
User session starts or endsHttpSessionListener
HTTP request begins or endsServletRequestListener
Attribute added/removed at app levelServletContextAttributeListener
Attribute added/removed at session levelHttpSessionAttributeListener
Attribute added/removed at request levelServletRequestAttributeListener

🚨 Bonus Tip:

  • Listeners do not block or control the flow (unlike filters).
  • They are passive observers — they listen and react.
This entry was posted in Без рубрики. Bookmark the permalink.