Why this matters
- Placing logic in the wrong layer (security in a controller, logging in a filter) creates maintenance nightmares.
- Filters run before Spring MVC; interceptors run after handler mapping — knowing the order prevents duplicate processing.
- The middleware stack is where correlation IDs, request logging, and authentication happen.
Filter vs interceptor
L1 · FresherServlet filters wrap the whole request; HandlerInterceptor runs around Spring MVC handler execution.
Security filter chain
L2 · IntermediateSpring Security installs its own filter chain before DispatcherServlet — order matters for JWT parsing.
OncePerRequestFilter
L3 · AdvancedExtend for request logging that must not double-run on forwards — common BookStore debugging tool.
WebMvcConfigurer
L4 · ExpertRegister interceptors for locale or tenant resolution without touching servlet APIs.
The request pipeline
Layers from outer to inner
- Servlet Filter — Servlet spec; runs before Spring. Compression, CORS headers, request logging.
- Security Filter Chain — Spring Security; authentication and authorization.
- DispatcherServlet — Spring MVC entry point; maps URL to handler.
- HandlerInterceptor — Pre/post/after-completion around controller execution.
- Controller — Your BookStore endpoint method.
Servlet filter
// learn:fragment
@Component
public class CorrelationIdFilter extends OncePerRequestFilter {
private static final String CORRELATION_HEADER = "X-Correlation-Id";
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain)
throws ServletException, IOException {
String correlationId = request.getHeader(CORRELATION_HEADER);
if (correlationId == null) {
correlationId = UUID.randomUUID().toString();
}
MDC.put("correlationId", correlationId);
response.setHeader(CORRELATION_HEADER, correlationId);
try {
chain.doFilter(request, response);
} finally {
MDC.remove("correlationId");
}
}
}
OncePerRequestFilter guarantees one execution per request, even with forwards.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 7 sections
- Handler interceptor
- Filter vs interceptor
- Filter ordering
- Security filter chain position
- A custom annotation on the handler
- @ControllerAdvice is not middleware
- Practical BookStore stack
Test yourself
Answer these before moving on — recall is what makes it stick.