Skip to main content
Advertisement

5.4 Filter and Interceptor

Learn the differences and usage of Filter and Interceptor, two powerful tools used for common request processing (authentication, data compression, logging, etc.) in web applications.

1. Filter

A Filter is a component that runs at the Servlet Container level. It processes tasks before and after a request reaches Spring's DispatcherServlet.

Characteristics

  • Defined in the J2EE standard specification.
  • Mainly used for encoding conversion, security filters (Spring Security), XSS defense, etc.
  • Can manipulate or replace ServletRequest and ServletResponse objects entirely.

Implementation Example (Logging Filter)

@Component
public class MyFilter implements Filter {

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("Filter: Before reaching DispatcherServlet");

chain.doFilter(request, response); // Pass to the next filter or servlet

System.out.println("Filter: Right before responding to the client");
}
}

2. Interceptor

An Interceptor is a component that runs within the Spring Context. It operates before and after the DispatcherServlet calls the controller.

Characteristics

  • A core feature of Spring MVC.
  • Mainly used for login checks, permission checks, logging API calls, etc.
  • Can access all Spring Beans, allowing for processing closely coupled with business logic.

Implementation Example (Authorization Interceptor)

@Component
public class AuthInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
System.out.println("Interceptor: Before calling the controller (preHandle)");
// Returning false prevents the request from reaching the controller
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
System.out.println("Interceptor: After the controller task is complete (postHandle)");
}
}

3. Comparison Between Filter and Interceptor

CategoryFilterInterceptor
ManagementServlet Container (e.g., Tomcat)Spring Container (Spring MVC)
LocationOutside DispatcherServletInside DispatcherServlet (Around Controller)
ObjectsServletRequest, ServletResponseHttpServletRequest, HttpServletResponse, Handler
UsageSecurity, Encoding, XSS DefenseSession check, Authorization, Detailed logs

4. Execution Order

  1. HTTP Request -> Filter(doFilter first half)
  2. Reach DispatcherServlet
  3. Interceptor(preHandle)
  4. Controller execution
  5. Interceptor(postHandle)
  6. Response generation (View)
  7. Interceptor(afterCompletion)
  8. Filter(doFilter second half) -> HTTP Response

5. Advanced: Reading Request Body in Filter (ContentCachingRequestWrapper)

A standard HttpServletRequest can read its InputStream only once. If you read the Request Body in a filter for logging, the controller will be unable to read it. To solve this, you can use ContentCachingRequestWrapper provided by Spring.

Wrapping Filter Implementation Example

@Component
public class CachingFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {

// Wrap request and response with cacheable wrapper objects
ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);

// Pass the wrapped objects to the next chain
filterChain.doFilter(requestWrapper, responseWrapper);

// Access the body after the business logic (controller) has finished
String requestBody = new String(requestWrapper.getContentAsByteArray());
System.out.println("Request Body: " + requestBody);

// You MUST copy the body to the response at the end so the client receives it
responseWrapper.copyBodyToResponse();
}
}

🎯 Key Points

  • Filter is a web standard technology, useful for filtering or transforming requests.
  • Interceptor is a Spring technology, advantageous for detailed controller control using Beans.
  • Spring Security handles authentication/authorization based on the Filter Chain.
Advertisement