Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 66 ยท Building REST APIs

Filters, Interceptors and Argument Resolvers

Run code around every request in Spring Boot: servlet filters, HandlerInterceptor, ordering, request logging, CORS and custom argument resolvers.

Some work belongs to every request rather than to one endpoint: logging how long it took, attaching a request id, checking an API key, adding a header, reading the current user. Copying that code into each controller method is tedious and easy to forget. Spring Boot offers three hooks that run around your controllers: servlet filters, handler interceptors and argument resolvers.

They look similar and are easy to mix up. This lesson explains where each one sits in the request path, what each can see, how to order them, and which to choose. We also cover the practical case of request logging and the right way to configure CORS. Security is built on filters as well; the full picture comes in Spring Security Fundamentals. If you want the plain servlet background first, read Filters and Listeners.

Real Spring code is read-only here. The TryIts model a filter chain and an interceptor pipeline in plain Java, so you can see the order of calls, which is the part people find confusing.

Where each hook sits

A request passes through layers. Outermost is the servlet container (Tomcat), which runs filters. Then comes Spring MVC's DispatcherServlet, which finds the controller method. Around that method run interceptors, and argument resolvers build the method's parameters.

flowchart LR
    A["Client"] --> B["Servlet filters"]
    B --> C["DispatcherServlet"]
    C --> D["Interceptor preHandle"]
    D --> E["Argument resolvers"]
    E --> F["Controller method"]
    F --> G["Interceptor postHandle / afterCompletion"]
    G --> B

A request goes in through filters and interceptors, and the response comes back out through them in reverse.

Choosing the right hook

Filter Servlet level. Sees every request, even static files.
Interceptor MVC level. Knows which controller method will run.
Argument resolver Builds a custom parameter, such as the current user.

Filter for raw HTTP, interceptor for handler-aware checks, resolver for parameters.

1 / 2

Servlet filters

A filter is the oldest and lowest-level hook. It implements jakarta.servlet.Filter, receives the request and response, and decides whether to call the rest of the chain. In Spring, extend OncePerRequestFilter, which guarantees one execution per request even when the request is forwarded internally:

Java
@Component
class RequestIdFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String id = Optional.ofNullable(request.getHeader("X-Request-Id"))
            .orElseGet(() -> UUID.randomUUID().toString());
        MDC.put("requestId", id);
        response.setHeader("X-Request-Id", id);
        try {
            chain.doFilter(request, response);   // everything after this runs inside
        } finally {
            MDC.clear();
        }
    }
}

Boot detects any Filter bean and registers it for all URLs. To limit it to some paths or set an exact position, wrap it in a FilterRegistrationBean:

Java
@Bean
FilterRegistrationBean<RequestIdFilter> requestIdFilter() {
    var registration = new FilterRegistrationBean<>(new RequestIdFilter());
    registration.addUrlPatterns("/api/*");
    registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return registration;
}

Two rules keep filters healthy. First, a filter that does not call chain.doFilter ends the request, which is exactly how an API-key check rejects a call, but it must write a response itself. Second, always do clean-up (like MDC.clear()) in a finally block, because Tomcat reuses threads and leftover thread-local data leaks into the next request.

The chain stand-in

A filter chain is a list of filters plus a final target. Each filter receives a next function it may call, skip, or wrap with code before and after. The first TryIt builds exactly that, with a timing filter on the outside, an API-key filter in the middle and a handler at the end.

Java A filter chain in plain Java

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

With the key, the call goes down the chain and back up (logging wraps everything). Without it, the API-key filter answers 401 and the controller never runs, but the logging filter still sees the response because it is further out. Order is therefore design: put cross-cutting things such as logging and request ids first, and security checks before business filters.

Handler interceptors

An interceptor lives inside Spring MVC. It implements HandlerInterceptor and has three callbacks:

  • preHandle runs before the controller method. Return false to stop the request.
  • postHandle runs after the method returns, before the response is written. It is not called if the method throws.
  • afterCompletion runs at the very end, always, even after an exception. Use it for clean-up and timing.

Register interceptors through a WebMvcConfigurer, where you can include or exclude URL patterns and set the order:

Java
@Configuration
class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuditInterceptor())
            .addPathPatterns("/api/**")
            .excludePathPatterns("/api/health")
            .order(1);
    }
}

The practical difference from a filter: an interceptor receives the handler object, so it can read annotations on the target method. That makes it a natural home for a custom annotation such as @RequiresAdmin or @RateLimited. It cannot replace the request or response objects, which only filters can do (for example, to compress or to cache the request body).

Java Interceptor order: pre, post, after

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the three outputs side by side. In the normal case pre runs in order (A, B) while post and after run in reverse (B, A). When B refuses, only A's afterCompletion runs, because B never completed its preHandle. When the controller throws, postHandle is skipped but afterCompletion still runs with the exception, so clean-up code is safe there. This mirrors how Spring's HandlerExecutionChain behaves.

Request logging

A typical first filter logs one line per request: method, path, status and duration. Spring ships CommonsRequestLoggingFilter for logging the request line and payload, but be careful with bodies: they can contain passwords, tokens and personal data. A safe default is to log method, path, status, duration and the request id, and to log bodies only in a development profile. Log the line in finally (filter) or afterCompletion (interceptor) so that failed requests are logged too. The Logging lesson shows how to put the request id into every log line with the MDC.

CORS

Browsers block a page on https://app.example.com from calling an API on https://api.example.com unless the API says it is allowed, using CORS headers. This is a browser rule, so curl and servers never hit it. In Spring MVC the clean way is one central configuration:

Java
@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/api/**")
        .allowedOrigins("https://app.example.com")
        .allowedMethods("GET", "POST", "PUT", "DELETE")
        .allowedHeaders("Content-Type", "Authorization")
        .maxAge(3600);
}

Name your real origins. allowedOrigins("*") together with credentials is rejected by browsers and is a bad idea in general. When Spring Security is on the classpath, CORS must also be enabled in the security filter chain (http.cors(...)), otherwise the security filter answers the browser's preflight request with 401 before MVC sees it. The security side of CORS is covered in CSRF, CORS and Secure Defaults.

Custom argument resolvers

Controller methods can take parameters that Spring does not know about, such as @CurrentUser User user. An argument resolver teaches MVC how to build such a parameter. It implements HandlerMethodArgumentResolver:

Java
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@interface CurrentUser {}

class CurrentUserResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CurrentUser.class)
            && parameter.getParameterType() == User.class;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mav,
                                  NativeWebRequest request, WebDataBinderFactory binder) {
        return userLookup.fromToken(request.getHeader("Authorization"));
    }
}

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
    resolvers.add(new CurrentUserResolver());
}

The controller then reads naturally and stays testable:

Java
@GetMapping("/me")
ProfileResponse me(@CurrentUser User user) { ... }

With Spring Security, you usually use the built-in @AuthenticationPrincipal instead of writing your own, but the pattern is the same for other request-derived values such as a tenant id, a locale or paging defaults.

The last TryIt is a mini argument resolver: it inspects a method's parameters with reflection, asks each resolver whether it supports the parameter, and fills the arguments before calling the method.

Java Resolving parameters by annotation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Real Spring has a long built-in list of resolvers (@PathVariable, @RequestParam, @RequestBody, Principal, Pageable and more). Your custom one joins that list, and the final error is a simplified version of what you see when a parameter type has no resolver.

If you need the same behavior around business methods (services, repositories) rather than HTTP requests, you do not want a filter or interceptor. Use Spring AOP or an annotation processed by a proxy instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which hook runs first for an incoming request?

    Filters belong to the servlet container and wrap the whole DispatcherServlet. Interceptors and argument resolvers run later, inside Spring MVC.
  2. 2. A filter does not call chain.doFilter(...). What happens?

    Not calling the chain stops processing. That is how an API-key filter rejects a call, but it is responsible for setting the status and body.
  3. 3. When is afterCompletion of a HandlerInterceptor called?

    afterCompletion is the clean-up callback. It runs for every interceptor whose preHandle returned true, whether the request succeeded or failed.
  4. 4. What is a good use of a custom HandlerMethodArgumentResolver?

    An argument resolver builds a custom controller parameter from the request, which keeps controllers short and easy to test.
  5. 5. Why did a browser request fail with 401 during a CORS preflight in an app that uses Spring Security?

    The security filters run before MVC. Without http.cors(...), they reject the unauthenticated preflight OPTIONS request before the MVC CORS mapping applies.

Summary

  • Filters run at the servlet level around everything; interceptors run inside Spring MVC and know the target handler; argument resolvers build controller parameters.
  • Extend OncePerRequestFilter; ordering decides who sees the request first, and a filter that skips chain.doFilter ends the request.
  • Interceptors have preHandle, postHandle and afterCompletion; the last always runs, in reverse order, for interceptors that passed preHandle.
  • Log method, path, status, duration and a request id; keep bodies and secrets out of logs.
  • Configure CORS centrally with named origins, and enable it in Spring Security too.
  • A custom HandlerMethodArgumentResolver gives you parameters like @CurrentUser.

Next: Calling Other Services (RestClient and HTTP Interfaces).