天天看点

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使用拦截器

以上为个人见解,如有误欢迎各位指正

继续阅读