> For the complete documentation index, see [llms.txt](https://petercheng7788.gitbook.io/developer-note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://petercheng7788.gitbook.io/developer-note/backend/spring/interceptor.md).

# 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

```java
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HasPermission {
}
```

```java
@HasPermission
@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto<Map<String, Object>>> userDetail(){
    ...
}
```

```java
@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......>
}
```

```java
@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

![](/files/Pufy6McbYnSEy0fFGNDp)

* 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
