Servlet Filters
What are Servlet Filters?
A Servlet Filter is a Java class that intercepts HTTP requests and responses before they reach a Servlet (or after the Servlet processes them). Filters implement the javax.servlet.Filter interface and are configured to intercept specific URL patterns.
Filters are ideal for cross-cutting concerns that apply to multiple Servlets:
- Authentication and authorization
- Logging and auditing
- Request/response compression
- Character encoding
- CORS headers
- Rate limiting
- Input validation/sanitization
package com.example.filters;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;
import java.io.*;
// Apply to all URLs
@WebFilter("/*")
public class LoggingFilter implements Filter {
private FilterConfig filterConfig;
// Called once when filter is initialized
@Override
public void init(FilterConfig config) throws ServletException {
this.filterConfig = config;
System.out.println("LoggingFilter initialized");
}
// Called for every request matching the URL pattern
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
long startTime = System.currentTimeMillis();
String uri = req.getRequestURI();
String method = req.getMethod();
String ip = req.getRemoteAddr();
System.out.println("[REQUEST] " + method + " " + uri + " from " + ip);
// Pass request to next filter or servlet
chain.doFilter(request, response);
// Post-processing (after servlet response)
long duration = System.currentTimeMillis() - startTime;
int status = resp.getStatus();
System.out.println("[RESPONSE] " + method + " " + uri
+ " -> " + status + " (" + duration + "ms)");
}
// Called once when filter is destroyed
@Override
public void destroy() {
System.out.println("LoggingFilter destroyed");
}
}
Authentication Filter
// Protect /admin/* URLs
@WebFilter("/admin/*")
public class AuthFilter implements Filter {
private static final String[] PUBLIC_PATHS = {"/login", "/register", "/public"};
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
String path = req.getRequestURI().substring(req.getContextPath().length());
// Check if path is public
for (String publicPath : PUBLIC_PATHS) {
if (path.startsWith(publicPath)) {
chain.doFilter(request, response); // Allow through
return;
}
}
// Check if user is logged in
HttpSession session = req.getSession(false);
boolean loggedIn = (session != null && session.getAttribute("username") != null);
if (loggedIn) {
chain.doFilter(request, response); // Allow through
} else {
// Redirect to login
resp.sendRedirect(req.getContextPath() + "/login?redirect=" + path);
}
}
@Override public void init(FilterConfig config) {}
@Override public void destroy() {}
}
<!-- Filter ordering is defined by order in web.xml -->
<!-- Filters execute in the order they are declared -->
<filter>
<filter-name>LoggingFilter</filter-name>
<filter-class>com.example.filters.LoggingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoggingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>AuthFilter</filter-name>
<filter-class>com.example.filters.AuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthFilter</filter-name>
<url-pattern>/admin/*</url-pattern>
</filter-mapping>
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.