2019-04-22 | spring | UNLOCK

Spring Boot - Interceptor


你可以在Spring Boot中在以下情况下执行操作:

  • 发送Request请求给Controller控制器前
  • 发送Response响应给Client客户端前
    比如,你可以使用拦截器在发送给控制器前添加请求头,并且在发送response响应给客户端前添加响应头。
    使用到SpringBoot拦截器功能,需要创建一个@Component注解标识的类并且实现HandlerInceptor接口。
    当你使用拦截器时,你需要了解三种方法,如下:
    • preHandle() : 前置函数是在发送request请求给控制器前实施的增强函数,这个函数应该返回true以返回response响应给客户端。
    • postHandle() : 后置函数是在发送response响应给客户端前的增强函数。
    • afterCompletion() : 完成函数是完成request请求和response响应后的增强函数。
      代码如下:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      package com.restfulapio.demo.interceptor;

      import org.springframework.stereotype.Component;
      import org.springframework.web.servlet.HandlerInterceptor;
      import org.springframework.web.servlet.ModelAndView;

      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;

      @Component
      public class ProducetServiceInterceptor implements HandlerInterceptor {
      @Override
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      System.out.println("Pre Handle method is Calling");
      return true;
      }
      @Override
      public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
      System.out.println("Post Handle method is Calling");
      }
      @Override
      public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
      System.out.println("Request and Response is completed");
      }
      }

你必须通过实现WebMvcConfigurer接口中的addInterceptors方法来使用InterceptorRegistry对象注册这个拦截器,代码如下:

Note: 在SpringBoot2.0及Spring 5.0 WebMvcConfigurerAdapter已被废弃,推荐直接实现WebMvcConfigurer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.restfulapio.demo.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Component
public class ProductServiceInterceptorAppconfig implements WebMvcConfigurer {

@Autowired
ProducetServiceInterceptor producetServiceInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(producetServiceInterceptor);
}
}

测试URL:GET: http://localhost:8080/products

可以看到Postman能正常访问api

应用运行控制台正常拦截Request和Response

评论加载中