Java.Servlet.Difference between Filters and Listeners

🧠 Main Differences Between Filter and Listener

FeatureFilterListener
What it isInterceptor of requests and responsesEvent handler for lifecycle events
When it runsEvery time a matching request comes inWhen a specific event happens (like app start, session create, request initialize)
Main purposePre-processing and post-processing of requests/responsesObserving and reacting to events
Example useAuthentication, logging, compression, modifying requests or responsesResource cleanup, monitoring session creation, app startup tasks
Works withServletRequest, ServletResponse, FilterChainServletContext, HttpSession, ServletRequest events
Configured by@WebFilter annotation or web.xml@WebListener annotation or web.xml
Flow control?Yes (you can stop the request or modify it!)No (just reacts, can’t control flow)

🎯 In simple words:

  • Filter = Interfere with request/response processing.
  • Listener = React to lifecycle events (e.g., “Hey, someone created a session!”)

🔥 Tiny Examples:

Filter example — Block requests if user is not logged in:

@WebFilter("/secure/*")
public class AuthFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession(false);

        if (session == null || session.getAttribute("user") == null) {
            ((HttpServletResponse) response).sendRedirect("/login.jsp");
        } else {
            chain.doFilter(request, response); // continue
        }
    }
}

Listener example — Log when a new session is created:

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

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

🛠️ Quick Memory Trick:

TermThink
FilterLike a security gate ➔ can allow, modify, or block
ListenerLike a security camera ➔ just observes and logs

⚡ Bonus: Types of Listeners

There are many listeners depending on what event you want to catch:

  • ServletContextListener ➔ app startup/shutdown
  • HttpSessionListener ➔ session creation/destruction
  • ServletRequestListener ➔ request creation/destruction
  • Plus attribute listeners: ServletContextAttributeListener, HttpSessionAttributeListener, etc.
This entry was posted in Без рубрики. Bookmark the permalink.