🧠 Main Differences Between Filter and Listener
Feature | Filter | Listener |
---|---|---|
What it is | Interceptor of requests and responses | Event handler for lifecycle events |
When it runs | Every time a matching request comes in | When a specific event happens (like app start, session create, request initialize) |
Main purpose | Pre-processing and post-processing of requests/responses | Observing and reacting to events |
Example use | Authentication, logging, compression, modifying requests or responses | Resource cleanup, monitoring session creation, app startup tasks |
Works with | ServletRequest , ServletResponse , FilterChain | ServletContext , 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:
Term | Think |
---|---|
Filter | Like a security gate ➔ can allow, modify, or block |
Listener | Like 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/shutdownHttpSessionListener
➔ session creation/destructionServletRequestListener
➔ request creation/destruction- Plus attribute listeners:
ServletContextAttributeListener
,HttpSessionAttributeListener
, etc.