Video in progress

Strong Middle 🌱 Spring

What is the difference between HandlerInterceptor and a Servlet Filter, and when do you use which?

Filter / HandlerInterceptor — Level: Servlet container / Spring MVC; Knows which controller it is: no / yes (HandlerMethod); Wraps request/response: yes (wrapper) / no; Before/after Spring Security: configurable / always after; Exception goes to @ControllerAdvice: no / yes

📖 Answer

Filter HandlerInterceptor
Level Servlet container Spring MVC
Knows which controller it is no yes (HandlerMethod)
Wraps request/response yes (wrapper) no
Before/after Spring Security configurable always after
Exception goes to @ControllerAdvice no yes

What fits a filter: putting a request id into MDC, ContentCachingRequestWrapper for logging the body, CORS, compression.

@Component
class RequestIdFilter extends OncePerRequestFilter {
    protected void doFilterInternal(HttpServletRequest rq, HttpServletResponse rs, FilterChain ch)
            throws ServletException, IOException {
        String id = Optional.ofNullable(rq.getHeader("X-Request-Id")).orElse(UUID.randomUUID().toString());
        MDC.put("requestId", id);
        rs.setHeader("X-Request-Id", id);
        try { ch.doFilter(rq, rs); } finally { MDC.remove("requestId"); }
    }
}

An interceptor fits checks based on a method annotation (for example @RequiresFeature("new-checkout")) or per-controller metrics.

Don't skip the MDC cleanup in finally; otherwise a pooled thread carries the old id into the next request.