Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What is the difference between a servlet Filter and a HandlerInterceptor? Give one use case for each.

A servlet Filter runs in the servlet container before DispatcherServlet, sees every request including static files and errors, and can wrap the request and response; a typical use is setting a correlation id in the logging MDC. A HandlerInterceptor runs inside DispatcherServlet after the handler has been chosen, so it knows which controller method will run; a typical use is checking an annotation on that method. Exceptions thrown in a filter are not handled by @ControllerAdvice, because they happen outside DispatcherServlet.

Why this question is asked

Filters and interceptors look similar: both run code before and after a request. Using the wrong one causes real bugs, such as an audit check that never sees the handler's annotations, or a filter exception that returns an ugly default error page instead of our JSON error format. Interviewers ask this to check that we know where each one sits in the request's path. In this answer, we will recap the path of a request, look at what a filter can do, then what an interceptor can do, compare them side by side, and see why exceptions behave differently.

1A Quick Recap of Where Each One Sits

A Spring MVC application runs inside a servlet container, such as the embedded Tomcat in Spring Boot. The container receives an HTTP request and passes it through a chain of filters. At the end of that chain sits a servlet, and in Spring MVC that servlet is DispatcherServlet, the front controller that decides which controller method handles the request.

A Filter belongs to the servlet specification, so it knows nothing about Spring MVC controllers. A HandlerInterceptor belongs to Spring MVC, and DispatcherServlet calls it after it has found the handler, the controller method that will run.

Step throughThe path of one request
  1. Embedded Tomcataccepts the request on a worker thread
  2. Servlet filterscorrelation id, Spring Security, logging
  3. DispatcherServletfinds the handler for the path
  4. HandlerInterceptorspreHandle, with the handler known
  5. Controller methodthe handler itself

5 layers, from the top down. Step through them one at a time.

Filters wrap everything below them; interceptors only wrap the handler.

2What a Filter Can Do

A filter's doFilter method receives the request, the response and the rest of the chain. Code before chain.doFilter() runs before everything else, code after it runs once the response has been produced. Because the filter passes the request and response objects along, it can replace them with wrappers, for example a ContentCachingRequestWrapper that keeps a copy of the body for logging.

This makes filters the right place for work that applies to every request and does not care which controller runs: correlation ids, character encoding, request logging, compression and, notably, Spring Security, which is itself a chain of filters.

Java
public class CorrelationIdFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
String id = Optional.ofNullable(req.getHeader("X-Correlation-Id"))
.orElse(UUID.randomUUID().toString());
MDC.put("correlationId", id); // every log line of this request carries the id
res.setHeader("X-Correlation-Id", id); // set before the body is written
try {
chain.doFilter(req, res); // the rest of the application runs here
} finally {
MDC.remove("correlationId"); // threads are reused, so always clean up
}
}
}

Notice the finally block. Container threads are pooled, so a value left in the MDC would leak into the next request served by the same thread.

3What an Interceptor Can Do

An interceptor has three callbacks. preHandle runs before the controller method and can stop the request by returning false. postHandle runs after the method returns but before a view is rendered. afterCompletion runs at the very end, even when an exception occurred. Each receives the handler object, which for an annotated controller is a HandlerMethod, so the interceptor can read the method's annotations.

That is the key difference: an interceptor knows what is about to run. It cannot replace the request or response objects, but it can make decisions based on the handler.

Java
public class FeatureFlagInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
if (handler instanceof HandlerMethod hm) {
RequiresFeature f = hm.getMethodAnnotation(RequiresFeature.class);
if (f != null && !flags.isOn(f.value())) {
res.sendError(404); // the endpoint appears not to exist
return false; // controller is not called
}
}
return true; // continue to the controller
}
}
// @RequiresFeature("new-checkout") on a method, flag off -> 404, flag on -> method runs

A filter could not do this without repeating Spring MVC's routing logic, because it does not know which method the URL maps to.

4Comparing Them Side by Side

The two tools overlap in timing but not in knowledge. The table sums up the practical differences.

Filter or interceptor?
QuestionFilterHandlerInterceptor
Defined byServlet specificationSpring MVC
Runsbefore DispatcherServletinside DispatcherServlet
Sees static files and /erroryes, every requestonly requests mapped to a handler
Knows the controller methodnoyes, through HandlerMethod
Can wrap request and responseyesno
Errors handled by @ControllerAdvicenoyes
Typical useMDC, logging, securityannotation checks, handler timing

5Why Exceptions in Filters Escape @ControllerAdvice

@ControllerAdvice exception handlers are run by DispatcherServlet's exception resolvers. They catch exceptions thrown while DispatcherServlet is processing a request, which includes interceptors and controllers. A filter runs outside DispatcherServlet, before it is called and after it returns, so an exception thrown there never reaches those resolvers.

What happens instead is that the exception propagates to the container. In Spring Boot, the container forwards to the /error path, and BasicErrorController produces Boot's default error body, not our ProblemDetail format. If a filter needs to reject a request, it should write the response itself, for example with status 401 and a JSON body, or delegate to a shared error writer, rather than throwing and hoping @ControllerAdvice will catch it.

Java
// In a filter:
throw new IllegalStateException("bad tenant");
// -> 500 from Boot's /error: {"timestamp":"...","status":500,"error":"Internal Server Error","path":"/api/orders"}
// The same exception thrown in a controller:
// -> handled by our @RestControllerAdvice: {"type":"about:blank","title":"Bad tenant","status":400}

6Follow-up questions

Can a Spring bean be used as a filter?

Yes. In Spring Boot, any bean of type Filter is registered with the container automatically, and it can use dependency injection like any other bean. For control over order and URL patterns, we register it through a FilterRegistrationBean instead.

Where does Spring Security fit?

Spring Security is a filter. Boot registers a single DelegatingFilterProxy that hands the request to Spring Security's FilterChainProxy, which runs its own internal chain of security filters. That is why security runs before DispatcherServlet and why authentication failures are handled by Security's entry points, not by @ControllerAdvice.

Why is postHandle less useful for REST controllers?

For @ResponseBody methods the response body is written and usually committed while the handler is processed, before postHandle runs, so headers set in postHandle are silently ignored. postHandle is mainly useful for adding model attributes before a view is rendered.

7Conclusion

In this answer, we saw that a filter is a servlet-level component that runs before DispatcherServlet for every request and can wrap the request and response, which makes it right for MDC, logging and security. An interceptor runs inside DispatcherServlet once the handler is known, which makes it right for decisions based on the controller method, such as annotation checks. Because filters run outside DispatcherServlet, their exceptions are not handled by @ControllerAdvice and end up at the container's error handling.

What to say in the interviewAbout 80 seconds aloud

Open with

The main difference is where they sit. A Filter is part of the servlet spec, and it runs in the container's filter chain before DispatcherServlet, so it sees every request, including static resources and error dispatches, and it can wrap the request and response objects.

Then, if they want more

An interceptor is a Spring MVC component that DispatcherServlet calls after it has picked the handler, so it knows which controller method is about to run, and it has preHandle, postHandle and afterCompletion.

For a filter, my standard example is a correlation id: read or generate X-Correlation-Id, put it in the MDC so every log line has it, set it on the response, and remove it in a finally block because threads are pooled. Spring Security is also a filter, which is why it runs before any controller.

For an interceptor, my example is checking an annotation on the handler method, say @RequiresFeature, and returning false from preHandle if the flag is off. A filter can't do that without re-implementing routing. One practical consequence I always mention: exceptions thrown in a filter are not handled by @ControllerAdvice, because those handlers are run by DispatcherServlet's exception resolvers.

A filter exception goes to the container and ends up at Boot's /error, so filters should write their own error responses.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is the difference between a servlet Filter and a HandlerInterceptor? Give one use...": https://scrivio-interview-library.netlify.app/spring-boot/mvc-architecture/a5476e7ebc/