OncePerRequestFilter and HandlerInterceptor

0

In a Spring Boot application, OncePerRequestFilter and HandlerInterceptor serve distinct purposes and are used in different contexts within the request processing lifecycle. Here’s a breakdown of their differences, use cases, and purposes:

Purpose:

  • OncePerRequestFilter is a type of servlet filter that ensures a particular filter is executed only once per request. This can be useful when you need to perform actions that should not be repeated multiple times for a single request, such as setting up or tearing down resources.

Use Cases:

  • Authentication and Authorization: Adding or checking authentication tokens or credentials.
  • Request Logging: Logging request details such as headers, parameters, or payloads.
  • Request Wrapping: Modifying the request or response objects.
  • CORS Handling: Adding CORS headers to responses.

Key Characteristics:

  • Extends javax.servlet.Filter.
  • Ensures the filter logic runs only once per request, avoiding duplicate processing.
  • Requires explicit registration in the filter chain.

Example:

public class MyOncePerRequestFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // Perform filter logic here
        filterChain.doFilter(request, response);
    }
}

Purpose:

  • HandlerInterceptor is used for intercepting requests handled by Spring MVC controllers. It allows you to perform operations before and after the request processing and even after the view is rendered.

Use Cases:

  • Pre-processing: Executing logic before the controller handles the request, such as checking user roles or logging request metadata.
  • Post-processing: Executing logic after the controller has processed the request but before the view is rendered, such as modifying the ModelAndView or adding additional data.
  • After Completion: Executing logic after the request is fully processed and the view is rendered, such as cleaning up resources.

Key Characteristics:

  • Implements the HandlerInterceptor interface.
  • Provides three callback methods: preHandle(), postHandle(), and afterCompletion().
  • Does not require explicit registration in the filter chain, but must be registered in the WebMvcConfigurer.

Example:

public class MyHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // Pre-processing logic
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // Post-processing logic
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // After completion logic
    }
}

Comparison Summary

FeatureOncePerRequestFilterHandlerInterceptor
PurposeExecute filter logic once per requestIntercept requests handled by Spring MVC
Lifecycle StageFilter chain (before request reaches dispatcher)Before and after controller processing
Typical Use CasesAuthentication, logging, CORS handlingPre-processing, post-processing, cleanup
Key MethodsdoFilterInternal()preHandle(), postHandle(), afterCompletion()
ConfigurationRegistered in the filter chainRegistered via WebMvcConfigurer

Choosing between OncePerRequestFilter and HandlerInterceptor depends on where you need to intercept the request and what kind of processing you need to perform. If you need to work within the filter chain, use OncePerRequestFilter. If you need to interact with the Spring MVC lifecycle, HandlerInterceptor is more appropriate.

Leave a Reply

Your email address will not be published. Required fields are marked *