SoFunction
Updated on 2025-04-13

Spring Boot Interceptor and Filter Detailed Tutorial (Example Detailed Explanation)

Detailed tutorial on Spring Boot Interceptor and Filter

1. Overview

1.1 What is an Interceptor?

The interceptor isSpring MVCComponents of the framework, based onAOP (System-oriented Programming)accomplish. It allows insertion of custom logic at different stages of request processing, such as before and after the Controller method is executed.

1.2 What is a filter?

The filter isJava Servlet SpecificationThe defined component that acts on all requests entering the container (such as Tomcat). It can pre-process and post-process before the request reaches the Servlet or before the response returns to the client.

1.3 Core Differences

characteristic Interceptor Filter
Framework Spring MVC Servlet API
Range of action Only Spring MVC managed requests All requests (including static resources)
rely Depend on Spring Container Relying on Servlet containers (such as Tomcat)
Execution timing Before and after the Controller method Before and after Servlet processing
Get Bean Supported (via Spring context) Not supported (need to inject through other methods)

2. Usage scenarios

2.1 Typical Application of Interceptor

  • Logging: Record request parameters and response time.
  • Permission verification: Check whether the user is logged in or has permissions.
  • Transaction Management: Enable/commit transactions before and after the Controller method.
  • Performance monitoring: Statistical interface time-consuming.

2.2 Typical applications of filters

  • Global character encoding: Unifiedly set the request/response encoding (such as UTF-8).
  • Cross-domain processing: Add CORS response header.
  • XSS Defense: Filter malicious scripts in request parameters.
  • Request compression: GZIP compression of the response content.

3. Implementation steps

3.1 Creating an Interceptor

step:

accomplishHandlerInterceptorInterface, override the following method:

  • preHandle(): Called before the Controller method is executed.
  • postHandle(): Called after the Controller method is executed and before the view is rendered.
  • afterCompletion(): Called after the request is completed (after view rendering).

Register the interceptor to the Spring MVC configuration.

Code example:

public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // Check whether the user is logged in        if (().getAttribute("user") == null) {
            ("/login");
            return false; // Interrupt request        }
        return true;
    }
}

Register the interceptor:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        (new AuthInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/login", "/static/**");
    }
}

Register multiple interceptors:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // The first interceptor: log (high priority)        (new LogInterceptor())
                .addPathPatterns("/**")       // Intercept all paths                .excludePathPatterns("/static/**"); // Exclude static resources        // The second interceptor: permissions (low priority)        (new AuthInterceptor())
                .addPathPatterns("/api/**");  // Intercept only /api paths    }
}

Key configuration options

Configuration method illustrate
addPathPatterns("/api") Specify the path to intercept (supports Ant style)
excludePathPatterns("/login") Exclude specific paths
order(1) Explicitly set order (default in registration order)

To specify the order manually, add:

(new LogInterceptor()).order(1);
(new AuthInterceptor()).order(2);

3.2 Create filters

step:

  • accomplishInterface, rewritedoFiltermethod.
  • Register filters to Servlet container (by annotation or configuration class).

Code example:

@WebFilter(urlPatterns = "/*")
public class LoggingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
            throws IOException, ServletException {
        ("Request Starts: " + ((HttpServletRequest) request).getRequestURI());
        (request, response); // Continue to execute subsequent filters or Servlets        ("Request End");
    }
}

Register filters (if @WebFilter is not used):

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean<LoggingFilter> loggingFilter() {
        FilterRegistrationBean<LoggingFilter> bean = new FilterRegistrationBean<>();
        (new LoggingFilter());
        ("/*");
        (1); // Set execution order        return bean;
    }
}

Notice:Make sure the main class is added@ServletComponentScanTo enable@WebFilterannotation.

4. Execution order and process

4.1 Execution order

  • FilterChain → 2. Interceptor (preHandle) → 3. Controller method → 4. Interceptor (postHandle) → 5. View rendering → 6. Interceptor (afterCompletion) → 7. Filter follow-up processing

4.2 Flow chart

Client → () → ()
       → Controller → ()
       → View rendering → ()
       → ()Follow-up processing → Client

5. FAQs and Solutions

Q1: How to control the execution order of multiple interceptors/filters?

  • Interceptor:pass()The order of decision.
  • Filter:pass()Set priority (the smaller the value, the more you execute it first).

Q2: How to get Spring-managed Beans in the interceptor?

Inject directly from Spring container:

public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService; // Direct injection}

Q3: How to modify the request parameters in the filter?

By customizingHttpServletRequestWrapper

public class ModifyRequestWrapper extends HttpServletRequestWrapper {
    // Rewrite getParameter and other methods to modify parameters}
// Replace Request object in Filter(new ModifyRequestWrapper(request), response);

Q4: How to deal with exceptions when interceptors and filters are executed?

  • Interceptor:existafterCompletionException handled in.
  • Filter:usetry-catchpack()

Q5: How to make an interceptor take effect globally?

useaddPathPatterns("/**")

(new LogInterceptor())
        .addPathPatterns("/**");

Q6: How to skip execution of a specific interceptor?

existpreHandleReturnfalse

@Override
public boolean preHandle(...) {
    if (Skip the condition) {
        return false; // Subsequent interceptors and controllers will not be executed    }
    return true;
}

Q7: How to share data between interceptors?

passtransfer:

//Storing data in the first interceptor("key", "value");
// Get it in the subsequent interceptorString value = (String) ("key");

6. Summary

Choose an interceptor or filter?

  • Requires access to Spring context or Controller information → Interceptor.
  • All requests (including static resources) need to be processed → Filters.

Best Practices

  • Priority is given to using interceptors to handle business-related logic.
  • Use filters to handle tasks (such as encoding, compression) of the underlying Servlet container.

This is the end of this article about the detailed tutorial on Spring Boot Interceptor and Filter. For more related Spring Boot Interceptor and Filter content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!