天天看點

springboot使用攔截器

攔截器:Interceptor 在AOP(Aspect-Oriented Programming)中用于在某個方法或字段被通路之前,進行攔截然後在之前或之後加入某些操作。比如日志,安全等。一般攔截器方法都是通過動态代理的方式實作。可以通過它來進行權限驗證,或者判斷使用者是否登陸

案例

  • 建立一個接口
/**
 * @author Gjing
 **/
@RestController
public class TestController {

    @PostMapping("/test")
    @ApiOperation(value = "測試", httpMethod = "POST")
    public ResponseEntity test() {
        return ResponseEntity.ok("ok");
    }
}           
  • 定義自己的攔截器并實作HandlerInterceptor接口
/**
 * @author Gjing
 **/
@Component
public class ApiInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (ParamUtil.isEmpty(token)) {
            throw new AuthException("Token cannot be null");
        }
        return true;
    }
}           
  • 配置攔截器
/**
 * @author Gjing
 **/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Resource
    private ApiInterceptor apiInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //addPathPatterns 用于添加攔截規則
        //excludePathPatterns 用于排除攔截
        registry.addInterceptor(apiInterceptor).addPathPatterns("/**")
                /*放行swagger*/
                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html")
                .excludePathPatterns("/")
                .excludePathPatterns("/login","/csrf");
    }
}           
  • 測試請求
  1. 不帶token
    springboot使用攔截器
  2. 帶token
    springboot使用攔截器

以上為個人見解,如有誤歡迎各位指正

繼續閱讀