当前位置:   article > 正文

SpringMVC 拦截器的使用_springmvc拦截器的使用

springmvc拦截器的使用

SpringMVC 拦截器的使用

Spring MVC中的拦截器(Interceptor)类似于Servlet中的过滤器(Filter),它主要用于拦截用户请求并做相应的处理。例如通过拦截器可以进行权限验证、记录请求信息的日志、判断用户是否登录等。

1. 拦截器的设计

首先所有的拦截器都需要实现HandlerInterceptor接口,该接口定义如代码所示:

public interface HandlerInterceptor {
    // 处理器执行前方法
    default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }
    
	// 处理器处理后方法
    default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    // 处理器完成后方法
    default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

在这里插入图片描述
其流程描述如下。

  • 执行preHandle方法,该方法会返回一个布尔值。如果为false,则结束所有流程;如果为true,则执行下一步。
  • 执行处理器逻辑,它包含控制器的功能。
  • 执行postHandle方法。
  • 执行视图解析和视图渲染。
  • 执行afterCompletion方法。

因为这个接口是Java 8的接口,所以3个方法都被声明为default,并且提供了空实现。当我们需要自己定义方法的时候,只需要实现HandlerInterceptor,覆盖其对应的方法即可。

2. 自定义拦截器

public class CustomInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("处理器前方法");
        // 返回true,不会拦截后续的处理
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("处理器后方法");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("处理完成方法");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

这里的代码实现了HandlerInterceptor,然后按照自己的需要重写了3个具体的拦截器方法。在这些方法中都打印了一些信息,这样就可以定位拦截器方法的执行顺序。

有了这个拦截器,Spring MVC并不会发现它,它还需要进行注册才能够拦截处理器,为此需要在配置文件中实现WebMvcConfigurer接口,最后覆盖其addInterceptors方法进行注册拦截器。

@Configuration
public class HandlerConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册拦截器到SpringMVC机制,然后它会返回一个拦截器注册
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(new CustomInterceptor());
        // 指定拦截匹配模式,限制拦截器拦截请求
        // 只会拦截与正则式“/interceptor/*”匹配的请求
        interceptorRegistration.addPathPatterns("/interceptor/*");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

这里还需要创建对应的请求方法,为此新建控制器来实现:

@Controller
@RequestMapping("/interceptor")
public class TestController {
    @GetMapping("/test")
    public String test(){
        System.out.println("执行处理器逻辑");
        return "/welcome";
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

定义了拦截“/interceptor/test”,而这个请求显然会被所创建的拦截器所拦截,所以只需要请求这个方法,请求就会被我们的拦截器拦截。欢迎页面

<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>深入Spring MVC</title>
    </head>
    <body>
    <h1><% System.out.println("视图渲染");%></h1>
    </body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

启动项目,访问http://localhost:8081/interceptor/test,控制台打印:

处理器前方法
执行处理器逻辑
处理器后方法
视图渲染
处理完成方法
  • 1
  • 2
  • 3
  • 4
  • 5

把拦截器的preHandle方法返回修改为false,启动项目,访问http://localhost:8081/interceptor/test,,控制台打印:

处理器前方法
  • 1

3. 多个拦截器的拦截顺序

实际上拦截器可能还不止一个。那么在多个拦截器环境中,它的各个方法执行的顺序是怎么样的呢?为了探讨这个问题,我们先创建3个拦截器。

public class MyInterceptor1 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(this.getClass().getSimpleName()+": 处理器前方法");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println(this.getClass().getSimpleName()+": 处理器器后方法");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println(this.getClass().getSimpleName()+": 处理器完成方法");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
public class MyInterceptor2 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(this.getClass().getSimpleName()+": 处理器前方法");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println(this.getClass().getSimpleName()+": 处理器器后方法");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println(this.getClass().getSimpleName()+": 处理器完成方法");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
public class MyInterceptor3 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(this.getClass().getSimpleName()+": 处理器前方法");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println(this.getClass().getSimpleName()+": 处理器器后方法");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println(this.getClass().getSimpleName()+": 处理器完成方法");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

注册多个拦截器:

这样这些拦截器都会拦截与"/interceptor/*"匹配的请求。这里使用浏览器再次请求/interceptor/test方法,则控制台打印:

MyInterceptor1: 处理器前方法
MyInterceptor2: 处理器前方法
MyInterceptor3: 处理器前方法
执行处理器逻辑
MyInterceptor3: 处理器器后方法
MyInterceptor2: 处理器器后方法
MyInterceptor1: 处理器器后方法
视图渲染
MyInterceptor3: 处理器完成方法
MyInterceptor2: 处理器完成方法
MyInterceptor1: 处理器完成方法
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

这个结果是责任链模式的规则,对于处理器前方法采用先注册先执行,而处理器后方法和完成方法则是先注册后执行的规则。

只是上述仅测试了处理器前(preHandle)方法返回为true的场景,在某些时候还可能返回为false,这个时候又如何呢?为此,可以将MyInterceptor2的preHandle方法修改返回为false,然后再进行测试,其日志如下:

MyInterceptor1: 处理器前方法
MyInterceptor2: 处理器前方法
MyInterceptor1: 处理器完成方法
  • 1
  • 2
  • 3

从上面的日志可以看出,处理器前(preHandle)方法会执行,但是一旦返回false,则后续的拦截器、处理器和所有拦截器的处理器后(postHandle)方法都不会被执行。完成方法afterCompletion则不一样,它只会执行返回true的拦截器的完成方法,而且顺序是先注册后执行。

将MyInterceptor3的preHandle方法修改返回为false,然后再进行测试,其日志如下:

MyInterceptor1: 处理器前方法
MyInterceptor2: 处理器前方法
MyInterceptor3: 处理器前方法
MyInterceptor2: 处理器完成方法
MyInterceptor1: 处理器完成方法
  • 1
  • 2
  • 3
  • 4
  • 5
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/972757
推荐阅读