Interceptor

Introduction

  • Can perform logic and stop before sending the request to the controller ot before sending the response to the client

  • There are 3 methods:

    • preHandle() method − This is used to perform operations before sending the request to the controller. This method should return true to return the response to the client.

    • postHandle() method − This is used to perform operations before sending the response to the client.

    • afterCompletion() method − This is used to perform operations after completing the request and response.

Implementation

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HasPermission {
}
@HasPermission
@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto<Map<String, Object>>> userDetail(){
    ...
}
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

  @Autowired PermissionInterceptor permissionInterceptor;
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(permissionInterceptor).order(Ordered.LOWEST_PRECEDENCE);
  <......Some other interceptor......>
}
@Component
public class PermissionInterceptor implements HandlerInterceptor {

  @Autowired
  PermissionService permissionService;

  @Override
  public boolean preHandle(
      HttpServletRequest request,
      HttpServletResponse response,
      Object handler
  ) throws Exception {
      if ((handler instanceof HandlerMethod) 
      && handlerMethod.hasMethodAnnotation(HasPermission.class)) {
      logger.info("Preflight request");
      return true;
    }
    return false;
  }
}

Difference between Filter

  • Filters intercept requests before they reach the DispatcherServlet

  • HandlerIntercepors, on the other hand, intercepts requests between the DispatcherServlet and our Controllers. This is done within the Spring MVC framework, providing access to the Handler and ModelAndView objects. This reduces duplication and allows for more fine-grained functionality

Last updated

Was this helpful?