赞
踩
SpringBoot拦截器未生效的可能原因:
注解是否添加齐全(@Component、@Configuration);
是否有多个配置类同时继承了WebMvcConfigurationSupport类,或实现了WebMvcConfigurer, 多个配置类只会生效前一个配置类,后一个配置类不会生效 ;
例:
swagger的配置类:
@Configuration public class ServletContextConfig extends WebMvcConfigurationSupport { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations("classpath:/static/"); registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); super.addResourceHandlers(registry); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } }
拦截器配置类:
/** * 拦截器 */ @Configuration public class WebConfigurer implements WebMvcConfigurer { @Autowired private TestInterceptor loginInterceptor; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { } @Override public void addInterceptors(InterceptorRegistry registry) { // 表示拦截所有的请求, registry.addInterceptor(loginInterceptor).addPathPatterns("/**"); } }
SpringBoot项目已经配置了Swagger用来管理api,然后再另外建一个拦截器配置类,此时拦截器配置类就不会生效,因为WebMvcConfigurer和WebMvcConfigurationSupport都是用来配置WebMvc的,WebMvcConfigurer只是WebMvcConfigurationSupport的一个扩展类,它并没有扩展新功能,只是为让用户更方便安全的添加自定义配置 ;
WebMvcConfigurer和WebMvcConfigurationSupport的区别说明: https://www.cnblogs.com/JonaLin/p/11633820.html
所以解决拦截器失效的方法是在一个配置类里重写这两个方法 ,如下
@Configuration public class ServletContextConfig extends WebMvcConfigurationSupport { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations("classpath:/static/"); registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); super.addResourceHandlers(registry); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } // 下面是拦截器内容 @Autowired private TestInterceptor testInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(testInterceptor).addPathPatterns("/**"); } }
TestInterceptor拦截器:
@Component
public class TestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.err.println("================>");
return false;
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。