Filters
A servlet filter wraps a request before it reaches a servlet and the response on the way out. You use filters for auth, logging, CORS, and wrapping streams. They are a chain of responsibility on HTTP.
Detailed Explanation
Filter.doFilter(request, response, chain) runs your before-logic, then chain.doFilter to call the rest of the chain and the servlet, then your after-logic. If you skip chain.doFilter, the servlet never runs. That is how an auth filter rejects a request: set 401 and return.
Filters are mapped by URL pattern. Order matters. In Jakarta you set @WebFilter plus FilterRegistrationBean order in Spring. Spring Security is a stack of filters in front of DispatcherServlet.
Request and response wrappers (HttpServletRequestWrapper) let you reread a body or add a header. Use them when a later filter or the servlet needs the original bytes.
You reach for a filter when the job is cross-cutting and should not live in every controller. You reach for a Spring HandlerInterceptor when you already have the MVC handler selected and need handler metadata. You reach for a controller advice for exception mapping.
The cost of a heavy filter on every request is latency. The cost of catching exceptions and not rethrowing is a swallowed failure and a 200. The cost of a filter that reads the body and does not wrap the request is an empty controller body.
Filters are singletons. No per-request fields. Thread-locals set in a filter must be removed in finally or the next request on that thread sees the last user.
Keep filters boring. Auth, request id, CORS, and gzip belong here. Business rules do not. A filter that loads a user from the database and applies discount policy is a hidden controller. Put that in a service the controller calls. Filters run for static paths and error dispatches too, so a heavy filter taxes every asset. Map them narrowly (/api/*) when they only apply to the API.
Code Examples
import java.io.IOException;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
public class ReadyFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
if (!"true".equals(req.getParameter("ready"))) {
((HttpServletResponse) resp).setStatus(403);
return; // no chain.doFilter: servlet skipped
}
chain.doFilter(req, resp);
}
}import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class LogFilter {
static void around(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)
throws Exception {
long t0 = System.nanoTime();
try {
chain.doFilter(req, resp);
} finally {
long ms = (System.nanoTime() - t0) / 1_000_000;
System.out.println(req.getRequestURI() + " " + ms);
}
}
}Common Gotchas
Filter order is part of the API
auth before business, CORS on the way out.
Consuming `InputStream` without a wrapper starves the controller
Consuming `InputStream` without a wrapper starves the controller