Servlet Filters in Java
Filters intercept requests before they reach Servlets and responses before they return to the client. They are ideal for cross-cutting concerns like authentication, logging, and encoding.
Filter Lifecycle
Filters implement javax.servlet.Filter with init(), doFilter(), and destroy() methods. The container calls doFilter() for every matching request. Filters are configured in web.xml or with @WebFilter annotation.
Filter Chain
@WebFilter("/admin/*")
public class AuthFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("user") == null) {
((HttpServletResponse) res).sendRedirect("/login");
return;
}
chain.doFilter(req, res); // Continue to next filter or servlet
}
}Common Filter Use Cases
Authentication
Verify login before allowing access to protected URLs.
Logging
Log request URL, method, duration, and client IP.
Encoding
Set request character encoding to UTF-8.
CORS
Add Access-Control headers for API endpoints.
Frequently Asked Questions
Filter order — how is it determined?▼
With @WebFilter, use the urlPatterns and dispatcherTypes attributes. In web.xml, the order of filter-mapping elements determines execution order. Spring Boot uses @Order annotation on FilterRegistrationBean.
