Java › Standard

Servlet filters and Spring MVC interceptors in practice

Trace an HTTP request through a Jakarta Servlet container and Spring MVC, then choose between a filter and a handler interceptor.

Servlet filters and Spring MVC interceptors in practice

A request trace ID belongs near the edge of the servlet chain. A check that depends on a controller annotation belongs where Spring MVC has already selected a handler. I use that boundary to choose between a filter and an interceptor.

The examples use Spring Boot 3.x, Jakarta Servlet 6.0, and Spring Framework 6.x.

The servlet contract and the embedded container

Tomcat, Jetty, and Undertow implement the Servlet contract in versions supported by their corresponding Spring Boot releases. The container accepts the HTTP connection and creates request and response objects. It then applies filter mappings and calls the target servlet. An MVC application normally uses Spring’s DispatcherServlet as that servlet.

This standard boundary allows controllers to stay the same when you switch between supported implementations. Dependency exclusions, container settings, and server-specific behavior still need attention. The Gradle example swaps the starter’s Tomcat dependency for Jetty.

1
2
3
4
5
6
7
// build.gradle - Replace embedded Tomcat with Jetty
dependencies {
    implementation('org.springframework.boot:spring-boot-starter-web') {
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
    }
    implementation 'org.springframework.boot:spring-boot-starter-jetty'
}

Check the resolved runtime dependencies after the swap. Running two server starters or using a container that expects the wrong Servlet API version can fail before any controller code runs.

Where a filter and an interceptor run

A servlet filter wraps the next step in the container chain. It can reject the request, change headers, or pass request and response wrappers downstream. Inside DispatcherServlet, Spring chooses a handler and constructs an MVC execution chain. A HandlerInterceptor can then inspect the selected handler, including a HandlerMethod and its annotations.

flowchart TD
    CLIENT["HTTP request"] --> FILTER["Servlet filter"]
    FILTER -->|"Continue chain"| DS["DispatcherServlet"]
    DS --> MAP["Map handler"]
    MAP --> INTERCEPTOR["HandlerInterceptor"]
    INTERCEPTOR --> CONTROLLER["Controller method"]
RequirementServlet filterSpring MVC interceptor
Applies before handler mappingYesNo
Can replace request or response with a wrapperYesReceives the objects already passed in
Can inspect controller method annotationsHandler has not been mapped yetYes, for a HandlerMethod
Typical workEncoding, CORS, request logging, security filter chainHandler metadata, controller-level audit, model attributes
Uncaught exceptionContainer handling or explicit delegationMVC exception resolution can apply

Exceptions thrown outside DispatcherServlet do not automatically enter @RestControllerAdvice. A filter that rejects requests can set the status and response body itself, or explicitly delegate to a configured HandlerExceptionResolver.

Managing a trace ID with OncePerRequestFilter

The trace filter puts a request identifier in the logging MDC, adds a corresponding response header, and calls the rest of the chain. It clears the MDC entry in finally. On a thread pool, that cleanup prevents a later request from inheriting the earlier ID when the same thread is reused.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// src/main/java/com/example/web/filter/RequestTraceFilter.java
package com.example.web.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestTraceFilter extends OncePerRequestFilter {

    private static final String TRACE_HEADER = "X-Request-Id";
    private static final String MDC_KEY = "requestId";

    @Override
    protected void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain filterChain
    ) throws ServletException, IOException {
        String requestId = request.getHeader(TRACE_HEADER);
        if (requestId == null || requestId.isBlank()) {
            requestId = UUID.randomUUID().toString();
        }

        MDC.put(MDC_KEY, requestId);
        response.setHeader(TRACE_HEADER, requestId);
        try {
            filterChain.doFilter(request, response);
        } finally {
            // Clear MDC before the pooled thread serves another request.
            MDC.remove(MDC_KEY);
        }
    }
}

OncePerRequestFilter coordinates invocation for a dispatch. Async and error dispatches have separate rules, and MDC is thread-local. If logs must retain the ID when work moves to another executor, propagate it to that worker explicitly and clear it there as well.

Checking a controller’s metadata in an interceptor

The MVC example defines @AdminOnly and checks for it after Spring resolves the handler. The interceptor first tests whether the handler is a HandlerMethod. Other handlers, such as some static resource handlers, do not expose controller method metadata.

1
2
3
4
5
6
7
8
// src/main/java/com/example/web/interceptor/AdminOnly.java
package com.example.web.interceptor;

import java.lang.annotation.*;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AdminOnly {}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// src/main/java/com/example/web/interceptor/AdminAccessInterceptor.java
package com.example.web.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AdminAccessInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(
        HttpServletRequest request,
        HttpServletResponse response,
        Object handler
    ) {
        if (!(handler instanceof HandlerMethod handlerMethod)) {
            return true;
        }

        boolean requiresAdmin = handlerMethod.hasMethodAnnotation(AdminOnly.class)
            || handlerMethod.getBeanType().isAnnotationPresent(AdminOnly.class);

        if (requiresAdmin && !"ADMIN".equals(request.getHeader("X-User-Role"))) {
            // MVC can route this exception through @RestControllerAdvice.
            throw new IllegalStateException("Administrator access is required.");
        }
        return true;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// src/main/java/com/example/web/config/WebMvcConfig.java
package com.example.web.config;

import com.example.web.interceptor.AdminAccessInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private final AdminAccessInterceptor adminAccessInterceptor;

    public WebMvcConfig(AdminAccessInterceptor adminAccessInterceptor) {
        this.adminAccessInterceptor = adminAccessInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(adminAccessInterceptor)
            .addPathPatterns("/api/**")
            .excludePathPatterns("/api/health", "/api/public/**");
    }
}

This example demonstrates where controller-specific policy can inspect annotations. A production authorization model also needs to account for endpoints outside that MVC mapping and requests dispatched through other paths. Use the Spring Security filter chain or method authorization where policy must cover those boundaries.

Verifying which layer owns the behavior

Send a normal request and confirm the trace ID is present while the request is processed. Then exercise a path that throws, and check that its next request starts with a fresh ID. On the MVC side, call both an annotated controller method and a handler with no matching annotation. Verify the status and body through the exception handling path the application actually configures.

This post is licensed under CC BY 4.0 by the author.