SoFunction
Updated on 2025-05-19

In-depth analysis of Spring Boot Interceptor and Filter (Difference, Implementation and Practical Practice Guide)

In-depth analysis of Spring Boot Interceptor and Filter: Guide to the difference, implementation and practical combat

1. Comparison of core concepts

1. Essential Differences

Dimension Filter Interceptor
Standard level Servlet specification (J2EE standard) Spring MVC framework mechanism
Range of action All requests (including static resources) Only handle Controller requests
Dependencies Not relying on Spring containers Fully integrated Spring IOC container
Execution order Execute first (before the DispatcherServlet) Execute after DispatcherServlet
Exception handling Spring's exception handling mechanism cannot be used directly Can be handled uniformly through @ControllerAdvice

2. Execution process diagram

HTTP Request
  ↓
Filter Chain(doFilter)
  ↓
DispatcherServlet
  ↓

  ↓
Controller Method
  ↓

  ↓
View Rendering(If there is)
  ↓

  ↓
Filter Chain(Return response)

2. Filter development guide

1. Basic implementation method

@Component
public class LogFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, 
                         FilterChain chain) throws IOException, ServletException {
        long startTime = ();
        HttpServletRequest req = (HttpServletRequest) request;
        // Pre-processing        ("Request URI: " + ());
        (request, response); // Release request        // Post-processing        long duration = () - startTime;
        ("Request completed in " + duration + "ms");
    }
}

2. Advanced configuration skills

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean<LogFilter> loggingFilter() {
        FilterRegistrationBean<LogFilter> registration = new FilterRegistrationBean<>();
        (new LogFilter());
        ("/api/*");
        (Ordered.HIGHEST_PRECEDENCE); // Set priority        return registration;
    }
}

Typical application scenarios

  • Request logging
  • Global character encoding settings
  • Cross-domain processing (CORS)
  • XSS Defense Filtering
  • Request content compression/decompression

3. Interceptor development guide

1. Standard implementation templates

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, 
                           HttpServletResponse response, 
                           Object handler) throws Exception {
        String token = ("Authorization");
        if (!validateToken(token)) {
            (401, "Invalid token");
            return false; // Interrupt request        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, 
                          HttpServletResponse response, 
                          Object handler,
                          ModelAndView modelAndView) throws Exception {
        // After the Controller method is executed, before the view rendering    }
    @Override
    public void afterCompletion(HttpServletRequest request, 
                               HttpServletResponse response, 
                               Object handler, 
                               Exception ex) throws Exception {
        // After the request is completely finished (including view rendering)    }
}

2. Register the interceptor configuration

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private AuthInterceptor authInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        (authInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/login", "/public/**");
    }
}

Typical application scenarios

  • Interface permission verification
  • Request parameter preprocessing
  • Time-consuming interface monitoring
  • Sensitive operation log
  • Check before data binding

4. In-depth analysis of core differences

1. Perform the order of experiments

The execution order when configuring multiple filters and interceptors:

Filter1 → Filter2 →  
→ Controller 
→  
→  
→ Filter2 → Filter1

2. Exception handling differences

// Handle exceptions in filterpublic void doFilter(...) {
    try {
        (request, response);
    } catch (Exception e) {
        (500, "Server Error");
    }
}
// Handle exceptions in the interceptor@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler()
    public ResponseEntity<?> handleException(Exception e) {
        return ().body("Error occurred");
    }
}

3. Asynchronous request processing

// Interceptor needs to implement AsyncHandlerInterceptor@Override
public void afterConcurrentHandlingStarted(HttpServletRequest request, 
                                          HttpServletResponse response, 
                                          Object handler) {
    // Special handling of asynchronous requests}

5. Best practices and selection strategies

1. Technology selection decision tree

Is it necessary to handle static resources?
├─ yes → Must useFilter
└─ no → 
   yesno需要访问Spring Bean?
   ├─ yes → chooseInterceptor
   └─ no → 
      yesno需要最早处理请求?
      ├─ yes → chooseFilter
      └─ no → 根据业务复杂度choose

2. Performance optimization suggestions

  • Filter: Avoid complex business logic in filters
  • Interceptor: The preHandle method is as light as possible
  • Both should be avoided:
    • Synchronous blocking operation
    • Frequent IO operations
    • Memory operation of large objects

3. Common trap avoidance

  • Filter
    • Forgot to call() causes the request to block
    • Modifying the request parameters does not use the Wrapper class
  • Interceptor
    • Modifying ModelAndView in postHandle causes NPE
    • Misuse afterCompletion in asynchronous request

6. Practical case demonstration

Case 1: Interface time-consuming monitoring system

// Interceptor implementationpublic class MetricsInterceptor implements HandlerInterceptor {
    private static final ThreadLocal<Long> startTime = new ThreadLocal<>();
    @Override
    public boolean preHandle(...) {
        (());
        return true;
    }
    @Override
    public void afterCompletion(...) {
        long duration = () - ();
        ((), duration);
        ();
    }
}

Case 2: Global anti-replay attack filter

public class ReplayAttackFilter implements Filter {
    private Cache<String, Boolean> requestCache = 
        ().expireAfterWrite(5, ).build();
    @Override
    public void doFilter(...) {
        String nonce = ("X-Nonce");
        if ((nonce) != null) {
            (400, "Duplicate request");
            return;
        }
        (nonce, true);
        (request, response);
    }
}

7. Expand knowledge

1. Differences from AOP

  • AOP
    • Implemented based on proxy mode
    • Can accurately control the specific method
    • More suitable for business-level section processing
  • Interceptor
    • Implemented based on HandlerMapping
    • Mainly for the HTTP request lifecycle
    • More suitable for general processing of the web layer

2. Advanced application scenarios

  • Filter chain: Implement the responsibility chain model
  • Interceptor stack: Combining multiple interception logics
  • Dynamically enable/disable: Integrated with the configuration center

Summary of suggestions

  • Priority to use interceptorsHandle the general logic of the web layer
  • Keep filtersFor underlying request processing
  • Complex scenarios canCombination useBoth
  • The production environment must be carried outPerformance pressure measurement

By rationally using filters and interceptors, developers can build a highly maintainable web application architecture. It is recommended to combine APM tools (such as SkyWalking) to monitor the execution efficiency of both to continuously optimize system performance.

This is the article about the in-depth analysis of Spring Boot Interceptor and Filter: Differences, Implementation and Practical Practice Guide. 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!