springboot拦截器排除路径失效

启动程序,需要过滤的路径一直失效。远代码如下:

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public TokenInterceptor tokenInterceptor() {
        return new TokenInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(tokenInterceptor()).excludePathPatterns("/login**");
        registry.addInterceptor(tokenInterceptor()).excludePathPatterns("/swagger**/**");
        super.addInterceptors(registry);
    }

}
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private TokenService validationService;

    /**
     * 根据请求不同对token进行处理
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader("token");
        boolean accessFlag = false;
        System.out.println("======"+request.getRequestURI());
        accessFlag = validationService.validateAccessToken(accessToken);
        if(accessFlag){
            validationService.updateToken(accessToken);
        }
        return accessFlag;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }
}

  

@SpringBootApplication
@ServletComponentScan
public class EmployeeApplication {

    public static void main(String[] args) {
        SpringApplication.run(EmployeeApplication.class, args);
    }
}
@ServletComponentScan和@Component注解可以不加
之后调整了一下WebMvcConfig里代码的写法得以实现,具体原理不是很清楚。
调整后代码如下:
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public TokenInterceptor tokenInterceptor() {
        return new TokenInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor()).excludePathPatterns("/users/login**","/swagger**/**").addPathPatterns("/**");
        super.addInterceptors(registry);
    }

}

 

posted on 2017-11-17 15:54  风清扬dyf  阅读(9971)  评论(0编辑  收藏  举报

导航