什么是拦截器?
就是你在访问控制层去做业务前后都做一些事,你调用我之前我先看看你有没有这个权限
拦截器和过滤器的区别:
归属不同:一个是Servlet技术一个是SpringMvc的技术
拦截的内容不同:过滤器Filter对所有访问进行加强,过滤器Interceptor仅仅针对SpringMvc的访问进行增强
简单的案例
1.声明拦截器的bean 实现 HandlerInterceptor 接口(注意扫描加载bean)
@Component
public class ProjectInterceptor implements HandlerInterceptor {
//拦截前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String connection = request.getHeader("Connection");
//handler里面封装了执行的方法
System.out.println(handler);
System.out.println("preHandle..." + connection);
//false表示终止原始操作
return true;
}
//拦截后
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//modelAndView封装了页面跳转相关的
System.out.println("postHandle...");
}
//拦截后并且再postHandle之后运行
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//ex 拿到异常
System.out.println("afterCompletion...");
}
}
2.定义配置类 设置拦截的请求和使用的拦截器
@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
protected void addInterceptors(InterceptorRegistry registry) {
//调用/books请求时间拦截 拦截器projectInterceptor
registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
}