Principles and Implementation of Filter and Interceptor

Principles and Implementation of Filter and Interceptor

Description
Filters and Interceptors are two important components in web frameworks used to process HTTP requests. They can execute specific logic before or after a request reaches the target handler (such as a Controller method). Although similar in functionality, they have key differences in implementation principles, scope of action, and usage scenarios. Understanding their distinctions and applicable scenarios is an important knowledge point in backend development.

Problem-Solving Process

  1. Basic Concepts and Positioning

    • Filter: Based on the Servlet specification, it is a standard component of Java web applications. It operates at the Servlet container level and can pre-process all requests entering the container, as well as post-process responses. A filter is like a "pipeline" through which requests and responses must pass.
    • Interceptor: It is a framework-level component, such as in Spring MVC. It works before and after the DispatcherServlet dispatches the request to a specific Controller, making it closer to business logic. An interceptor is like a "checkpoint" that only functions at key nodes within the framework.
  2. In-Depth Analysis of Implementation Principles

    Filter Implementation Mechanism:

    • A filter implements the javax.servlet.Filter interface and overrides three core methods:
      public class LogFilter implements Filter {
          @Override
          public void init(FilterConfig filterConfig) throws ServletException {
              // Initialization logic
          }
      
          @Override
          public void doFilter(ServletRequest request, ServletResponse response,
                             FilterChain chain) throws IOException, ServletException {
              // 1. Pre-processing before the request reaches the target (e.g., logging, permission checking)
              long startTime = System.currentTimeMillis();
      
              // 2. Call chain.doFilter() to pass control to the next filter or target Servlet
              chain.doFilter(request, response);
      
              // 3. Post-processing after the target processing is complete (e.g., recording time consumption, modifying response headers)
              long cost = System.currentTimeMillis() - startTime;
              System.out.println("Request processing time: " + cost + "ms");
          }
      
          @Override
          public void destroy() {
              // Resource cleanup logic
          }
      }
      
    • The filter chain (FilterChain) maintains the execution order of filters, implemented via the Chain of Responsibility pattern.

    Interceptor Implementation Mechanism:

    • An interceptor implements the HandlerInterceptor interface and overrides three key methods:
      public class AuthInterceptor implements HandlerInterceptor {
          @Override
          public boolean preHandle(HttpServletRequest request,
                                 HttpServletResponse response, Object handler) {
              // Called before the Controller method executes
              // Returns true to continue execution, false to interrupt the flow
              if (!checkAuth(request)) {
                  response.sendError(403, "No access permission");
                  return false;
              }
              return true;
          }
      
          @Override
          public void postHandle(HttpServletRequest request,
                               HttpServletResponse response, Object handler,
                               ModelAndView modelAndView) {
              // Called after the Controller method executes, before view rendering
              // Can modify ModelAndView
          }
      
          @Override
          public void afterCompletion(HttpServletRequest request,
                                    HttpServletResponse response,
                                    Object handler, Exception ex) {
              // Called after the entire request is complete (view has been rendered)
              // Suitable for resource cleanup, exception logging
          }
      }
      
  3. Execution Order and Scope Comparison

    • Complete Execution Flow (taking Spring MVC as an example):

      1. HTTP Request → Servlet Container
      2. Pass through all configured filters (in the order configured in web.xml)
      3. Reach DispatcherServlet (Spring MVC front controller)
      4. Execute the preHandle method of interceptors (in registration order)
      5. Execute the target Controller method
      6. Execute the postHandle method of interceptors (in reverse registration order)
      7. View rendering
      8. Execute the afterCompletion method of interceptors (in reverse registration order)
      9. Response undergoes post-processing by filters (in reverse order of configuration in web.xml)
    • Scope Differences:

      • Filter: Can filter all requests (static resources, JSP, Controller, etc.)
      • Interceptor: Only effective for requests managed by Spring Controllers
  4. Typical Application Scenarios

    • Scenarios Suitable for Filters:

      • Request/response encoding settings (CharacterEncodingFilter)
      • Cross-origin request handling (CORS Filter)
      • Sensitive word filtering, XSS protection
      • GZIP compression of responses
    • Scenarios Suitable for Interceptors:

      • User authentication and authorization checks
      • Request logging (when business parameters are needed)
      • Interface execution time statistics
      • Unified exception handling and data packaging
  5. Advanced Features and Best Practices

    • Filter Registration Methods:

      • Traditional web.xml configuration
      • Using @Component + @Order in Spring Boot
    • Interceptor Configuration Example:

      @Configuration
      public class WebConfig implements WebMvcConfigurer {
          @Override
          public void addInterceptors(InterceptorRegistry registry) {
              registry.addInterceptor(new AuthInterceptor())
                     .addPathPatterns("/api/**")  // Intercept paths
                     .excludePathPatterns("/api/public/**"); // Exclude paths
          }
      }
      

Key Summary

  • Filters operate at a lower level (Servlet container level), while interceptors operate at the framework level.
  • Filters can obtain the original ServletRequest/Response, while interceptors obtain framework-encapsulated objects.
  • Interceptors can directly obtain information about the Controller method handling the request, making them more suitable for business-related processing.
  • In practical projects, they are often used in combination: filters handle general technical issues, while interceptors handle business cross-cutting concerns.