Blog

Spring Filter Or Interceptor? Choose The Boundary You Need

similar hooks, different contracts
An HTTP request passing through servlet, MVC, controller, and method boundary gates

Filters and interceptors both run “around requests,” which is true in the same way that a building door and an office door are both doors. Placement changes what they can see and protect.

Filter: Servlet Boundary

A filter runs in the servlet chain before Spring MVC selects a controller. It is a good place for correlation IDs, raw request wrapping, security mechanisms integrated at that layer, and headers that must apply even when no controller matches.

class CorrelationFilter extends OncePerRequestFilter {
    protected void doFilterInternal(HttpServletRequest request,
            HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String id = correlationId(request);
        MDC.put("correlationId", id);
        try {
            response.setHeader("X-Correlation-Id", id);
            chain.doFilter(request, response);
        } finally {
            MDC.remove("correlationId");
        }
    }
}

Async dispatch and error dispatch need deliberate handling. “Once” has framework semantics, not magic global uniqueness.

Interceptor: MVC Boundary

An MVC interceptor runs after handler mapping, so it can inspect the chosen handler and annotations. This fits controller-level authorization metadata, locale decisions, or request timing tied to route information.

It is not ideal for changing raw request bodies, and it will not cover traffic handled outside MVC.

Advice And Aspects Are Other Tools

Use controller advice for response and exception shaping. Use method security or an aspect when the rule belongs to a service operation rather than HTTP transport.

Do not implement the same authentication check in all four places. Pick the earliest boundary with enough context, then test bypass paths such as errors, static resources, async dispatch, and non-controller entry points.

The correct hook is the one whose contract matches the invariant. Convenience is secondary.