拦截器
拦截器
interceptor要放在contorller下比较方便
1.先创建拦截器类,并注册为bean
2.再springmvc配置类里扫描到拦截器
3.再在SpringMvcSupport类里添加拦截路径
@Component
public class ProjectInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle...");
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle...");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion...");
}
}
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
}
}
@Configuration
@ComponentScan({"com.example.controller","com.example.config"})
@EnableWebMvc
public class SpringMvcConfig {
}
也可以直接让SpringMvcConfig类实现WebMvcConfigurer接口,效果相同
public class SpringMvcConfig implements WebMvcConfigurer {
@Autowired
private ProjectInterceptor projectInterceptor;
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
}
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/page/**").addResourceLocations("/page/");
}
}
多拦截器执行顺序
配置多个拦截器时,形成拦截器链
先运行1后运行2
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
registry.addInterceptor(projectInterceptor2).addPathPatterns("/books","/books/*");
}
形成拦截器链