1、概述
过滤器属于Servlet范畴的API,与Spring 没什么关系。
Web开发中,我们除了使用 Filter 来过滤请web求外,还可以使用Spring提供的HandlerInterceptor(拦截器)。
2、实现方法
第一种方式是实现了Spring 的HandlerInterceptor 接口,或者是这个类继承实现了HandlerInterceptor 接口的类,HandlerInterceptorAdapter ;
2.1 、拦截器接口(HandlerInterceptor)
package org.springframework.web.servlet;
public interface HandlerInterceptor {
boolean preHandle(
HttpServletRequest request, HttpServletResponse response,
Object handler)
throws Exception;
void postHandle(
HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView)
throws Exception;
void afterCompletion(
HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex)
throws Exception;
}
我们可能注意到拦截器一个有3个回调方法,而一般的过滤器Filter才两个,这是怎么回事呢?马上分析。
preHandle:预处理回调方法,实现处理器的预处理
返回值:true表示继续流程(如调用下一个拦截器或处理器);
false表示流程中断(如登录检查失败),不会继续调用其他的拦截器或处理器,此时我们需要通过response来产生响应;
postHandle:后处理回调方法,实现处理器的后处理(但在渲染视图之前),此时我们可以通过modelAndView(模型和视图对象)对模型数据进行处理或对视图进行处理,modelAndView也可能为null。
afterCompletion:整个请求处理完毕回调方法,即在视图渲染完毕时回调,如性能监控中我们可以在此记录结束时间并输出消耗时间,还可以进行一些资源清理,类似于try-catch-finally中的finally,但仅调用处理器执行链中preHandle返回true的拦截器的afterCompletion。
2.2、拦截器适配器(HandlerInterceptortAdapter)
有时候我们可能只需要实现三个回调方法中的某一个,如果实现HandlerInterceptor接口的话,三个方法必须实现,不管你需不需要,此时spring提供了一个HandlerInterceptorAdapter适配器(一种适配器设计模式的实现),允许我们只实现需要的回调方法。
public abstract class HandlerInterceptorAdapter implements HandlerInterceptor {
//省略代码 此处所以三个回调方法都是空实现,preHandle返回true。
}
2.3 图示流程(下面两个图来源于张开涛博客)
1) 正常流程图
2) 异常流程图
中断流程中,比如是HandlerInterceptor4中断的流程(preHandle返回false),此处仅调用它之前拦截器的preHandle返回true的afterCompletion方法。
3. 实战
Spring boot 实现自定义拦截器只需要3步:
1、创建我们自己的拦截器类并实现 HandlerInterceptor 接口或者HandlerInterceptorAdapt。
2、创建一个Java类继承WebMvcConfigurerAdapter,并重写 addInterceptors 方法。
3、实例化我们自定义的拦截器,然后将对像手动添加到拦截器链中(在addInterceptors方法中添加)。
创建自定义的Interceptor
public class MyInterceptor1 extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("第一种规则合法性校验");
return true;// 只有返回true才会继续向下执行,返回false取消当前请求
}
}
public class MyInterceptor2 extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("第二种规则合法性校验");
return true;// 只有返回true才会继续向下执行,返回false取消当前请求
}
}
实例化自定义拦截器
public class MyWebAppConfigurer
extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 多个拦截器组成一个拦截器链
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
// 还可以指定拦截顺序.order()
registry.addInterceptor(new MyInterceptor1()).order(1).addPathPatterns("/**");
registry.addInterceptor(new MyInterceptor2()).order(2).addPathPatterns("/**");
super.addInterceptors(registry);
}
}
4、总结:
通过上面的几个步骤就可以实现在Spring boot 中自定义拦截器,并且指明拦截的顺序。
参考文章:
http://jinnianshilongnian.iteye.com/blog/1670856
https://blog.youkuaiyun.com/catoop/article/details/50501696