1.编写SpringMVC中Interceptor拦截器方法
2.在SpringmvcConfig配置类中进行添加拦截器,并配置拦截器路径
@Configuration
@ComponentScan({"com.zkr.controller", "com.zkr.config"})
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer{
@Autowired
private ProjectInterceptor projectInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置多拦截器
registry.addInterceptor(projectInterceptor)
.addPathPatterns("/interceptorTest", "/interceptorTest/*");
}
}
3.进行调试路径,发现拦截器并未生效!!!
排查原因:
而我们的添加拦截器配置是在mvc的配置文件中直接继承的
- 而容器中只需要维护一个WebMvcConfigurationSupport即可,多了则会失效
- 在使用@EnableWebMvc的情况下,又去继承WebMvcConfigurationSupport进行配置所以导致了失效也就是说我多写了一个
知道原因后我们也就不难解决
只需要将mvc添加拦截器的代码写到SpringMvcConfigSupport中就可以定义多个 SpringMvcConfigSupport类的问题
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Autowired
private ProjectInterceptor projectInterceptor;
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**")
.addResourceLocations("/pages/");
registry.addResourceHandler("/css/**")
.addResourceLocations("/css/");
registry.addResourceHandler("/js/**")
.addResourceLocations("/js/");
registry.addResourceHandler("/plugins/**")
.addResourceLocations("/plugins/");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置多拦截器
registry.addInterceptor(projectInterceptor)
.addPathPatterns("/interceptorTest", "/interceptorTest/*");
}
}
@Configuration
@ComponentScan({"com.itheima.controller", "com.itheima.config"})
@EnableWebMvc
public class SpringMvcConfig{
}
此时在进行,发现拦截器失效的问题就可以解决了,ok下课