前言
上一篇我们介绍了 servlet,filter(过滤器),listener(监听器)在 spring-boot 中的注册, 这次学习 interceptor(拦截器)的运用. 其实 interceptor(拦截器)和 filter(过滤器)很相似, 都用于拦截过滤请求, 只是 filter 是 servlet 范畴的, 今天我们要学习的是 Spring 提供的 HandlerInterceptor(拦截器), 用到了其中比较重要的类: webMvcConfigurer.
正文
拦截器的学习
创建自己的拦截器类并实现 HandlerInterceptor 接口
- public class MyInterceptor implements HandlerInterceptor {
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- System.out.println("在请求处理之前进行调用");
- return true;//true 才会向下执行 false 取消当前请求
- }
- @Override
- public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
- System.out.println("请求处理之后进行调用");
- }
- @Override
- public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
- System.out.println("整个请求结束之后被调用");
- }
- }
注: 从这里也可以看出来拦截器比过滤器更为精细, 在 request 被响应之前, request 被响应之后, 视图渲染之前以及 request 全部结束之后都可以进行控制. 虽然不能像 filter 一样修改 request 的内容, 但是可以通过抛出异常 (或者返回 false) 来取消 request 的执行
创建一个 Java 类(
MyWebMvcConfigurer.java
)继承 WebMvcConfigurer, 并重写 addInterceptors 方法.
- @Configuration
- public class MyWebMvcConfigurer implements WebMvcConfigurer {
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- }
- }
实例化我们自定义的拦截器(MyInterceptor ), 将对像添加到 addInterceptors 方法中
- @Configuration
- public class MyWebMvcConfigurer implements WebMvcConfigurer {
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**")
- }
- }
启动程序, 浏览器访问:
http://localhost:8080/index
, 结合上一遍文章, 控制台输出如下信息 (过滤器和监听器的学习请移步上一篇文章: Spring boot 学习 (七) 之 servlet,filter(过滤器),listener(监听器) 的学习):
执行过滤操作
在请求处理之前进行调用
请求处理之后进行调用
监听器 sessiom 被创建
整个请求结束之后被调用
总结
只有经过 DispatcherServlet (spring-boot 默认为 "/*")的请求, 才会走拦截器链, 我们自定义的 Servlet 请求是不会被拦截的, 比如我们自定义的 Servlet 地址 : http://localhost:8080/user/myservlet 是不会被拦截器拦截的, 因为他没有经过 DispatcherServlet 请求. 下面这个是自定义的 servlet, 他不会走拦截器链
- @WebServlet(urlPatterns="/user/*", description="说明")
- public class MyServlet extends HttpServlet {
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- System.out.println("》》》》》》doPost 方法执行》》》》》》");
- }
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- System.out.println("》》》》》》doGet 方法执行》》》》》》");
- doPost(req, resp);
- }
- }
原创作者: 梦凌小样
来源: http://www.jianshu.com/p/518ad8b10334