SpringBoot study notes (17): Custom interceptors

SpringBoot study notes (17): Custom interceptors

Quick Start 

  Interceptors similar filter, but the interceptor provide finer control capability , which can intercept a request to process two nodes:

  • Before sending the request to the Controller
  • In response to the Client before

  For example, you can use the request interceptor in the header is added before sending the request to the controller, and adding the response header before sending a response to the client.

Creating interceptor

  Create an interceptor, HandlerInterceptor need to implement the interface, there are three ways to accomplish his interception

  • preHandle (): for performing the operations prior to the request to the controller. This method should return true to the response back to the client .

  • postHandle (): for performing the operations prior to the response result is sent to the client.

  • afterCompletion (): After the operation is performed in response to the request for all over.

  An interceptor custom code as follows:

@Component
public class ProductServiceInterceptor implements HandlerInterceptor {
   @Override
   public boolean preHandle(
      HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      
      return true;
   }
   @Override
   public void postHandle(
      HttpServletRequest request, HttpServletResponse response, Object handler, 
      ModelAndView modelAndView) throws Exception {}
   
   @Override
   public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
      Object handler, Exception exception) throws Exception {}
}

Registration interceptor

  After the interceptor, you must register the Interceptor to WebMvcConfigurerAdapter InterceptorRegistry , as shown below

@Component
public class ProductServiceInterceptorAppConfig extends WebMvcConfigurerAdapter {
   @Autowired
   ProductServiceInterceptor productServiceInterceptor;

   @Override
   public void addInterceptors(InterceptorRegistry registry) {
      registry.addInterceptor(productServiceInterceptor);
   }
}

  

Guess you like

Origin www.cnblogs.com/MrSaver/p/11201867.html