Spring MVC 拦截器总结
1.简介
Spring MVC提供了拦截器方便在接口调用前后进行一些通用处理。
2.步骤
1.实现一个拦截器类,共有三处拦截时机:
public class Interceptor1 implements HandlerInterceptor {//实现HandlerInterceptor接口
//执行handler之前调用
//编码格式处理,登录保护,权限处理
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Interceptor1.preHandle");
return true;//拒绝还是通过
}
//handler执行完毕后执行
//检查敏感词汇
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("Interceptor1.postHandle");
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
//整体处理完毕执行
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("Interceptor1.afterCompletion");
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
2.在配置类中注册拦截类:
public class MvcConfig implements WebMvcConfigurer {//实现WebMvcConfigurer接口
...
@Override
public void addInterceptors(InterceptorRegistry registry){
//方法 1.注册拦截类,拦截全部请求
registry.addInterceptor(new Interceptor1());
//方法 2.指定地址拦截
//通配符:* :一层字符 **:多层字符
registry.addInterceptor(new Interceptor1())
.addPathPatterns("/product/**");
//方法 3.排除拦截
registry.addInterceptor(new Interceptor1())
.addPathPatterns("/user/***").excludePathPatterns("/user/data1");
//如果有多个拦截类优先级如何?
registry.addInterceptor(new Interceptor1())//先声明优先级高,先进后出
.addPathPatterns("/product/**");
registry.addInterceptor(new Interceptor2())//后声明优先级低,后进先出
.addPathPatterns("/product/**");
}