JavaSpringBoot精选

springboot使用拦截器

2019-06-17  本文已影响0人  阿靖哦

拦截器:Interceptor 在AOP(Aspect-Oriented Programming)中用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。比如日志,安全等。一般拦截器方法都是通过动态代理的方式实现。可以通过它来进行权限验证,或者判断用户是否登陆

案例

/**
 * @author Gjing
 **/
@RestController
public class TestController {

    @PostMapping("/test")
    @ApiOperation(value = "测试", httpMethod = "POST")
    public ResponseEntity test() {
        return ResponseEntity.ok("ok");
    }
}
/**
 * @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


    1560742368(1).jpg
  2. 带token


    1560742349(1).jpg

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

上一篇下一篇

猜你喜欢

热点阅读