# 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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://petercheng7788.gitbook.io/developer-note/backend/spring/interceptor.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
