zoukankan      html  css  js  c++  java
  • springMVC之mvc:interceptors拦截器的用法

    参考:感谢各位辛苦整理!

      https://blog.csdn.net/qq_35246620/article/details/68487904

      https://www.cnblogs.com/lcngu/p/7096597.html

      https://www.cnblogs.com/daimajun/p/7172208.html

      https://blog.csdn.net/wscrf/article/details/72770853

    想对Spring MVC拦截器的用法做一个详细的整理,从网上搜了一下,发现有人整理的很好(https://www.cnblogs.com/lcngu/p/7096597.html),特记录如下

    1. 拦截器的实现方式

      在 Spring 框架之中,咱们要想实现拦截器的功能,主要通过两种途径,第一种是实现HandlerInterceptor接口,第二种是实现WebRequestInterceptor接口。

      其中第一种方法较为常用,在HandlerInterceptor接口中,定义了 3 个方法,分别为preHandle()postHandle()afterCompletion(),咱们就是通过复写这 3 个方法来对用户的请求进行拦截处理的。因此,咱们可以通过直接实现HandlerInterceptor接口来实现拦截器的功能。

    2. 配置拦截器

      在spring MVC项目的配置文件dispatcher-servlet.xml中,添加拦截器配置,如下所示

    <!-- 配置用于session验证的拦截器 -->
    <!-- 
        如果有多个拦截器满足拦截处理的要求,则依据配置的先后顺序来执行
     -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!-- 拦截所有的请求,这个必须写在前面,也就是写在【不拦截】的上面 -->
            <mvc:mapping path="/**" />
            <!-- 但是排除下面这些,也就是不拦截请求 -->
            <mvc:exclude-mapping path="/login.html" />
            <mvc:exclude-mapping path="/account/login.do" />
            <mvc:exclude-mapping path="/account/regist.do" />
            <!-- 拦截器java代码路径 -->
            <bean class="com.msym.cloudnote.interceptors.LogsInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>

      【说明】:

        1)mvc:mapping 拦截器路径配置,其中/** 的意思是所有文件夹及里面的子文件夹,(/*是所有文件夹,不含子文件夹,/是web项目的根目录,三者的作用需要深入研究)

        2)mvc:exclude-mapping 拦截器不需要拦截的路径

        3)mvc:mapping(拦截)一定要写于mvc:exclude-mapping之前

    3. 拦截器代码

    public class LogsInterceptor extends HandlerInterceptorAdapter {
    
        private static final Logger logger = LoggerFactory.getLogger(LogsInterceptor.class);
        
        private  NamedThreadLocal<String> logContext = new NamedThreadLocal<String>("log-id");
    
        @Autowired
        private TLogDao logDao;
    
        /**
         * preHandle方法是进行处理器拦截用的,顾名思义,该方法将在Controller处理之前进行调用,
         * SpringMVC中的Interceptor拦截器是链式的,可以同时存在多个Interceptor,
         * 然后SpringMVC会根据声明的前后顺序一个接一个的执行,
         * 而且所有的Interceptor中的preHandle方法都会在Controller方法调用之前调用。
         * SpringMVC的这种Interceptor链式结构也是可以进行中断的,
         * 这种中断方式是令preHandle的返回值为false,当preHandle的返回值为false的时候整个请求就结束了。
         */
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            String host = request.getRemoteHost();
            String url = request.getRequestURI();
            TLogEntity entity = new TLogEntity();
            entity.setCreateTime(new Timestamp(System.currentTimeMillis()));
            entity.setCreateUser("admin");
            entity.setIpAddress(host);
            entity.setLogUrl(url);
            entity.setIsSuccess("N");
            logDao.save(entity);
            logContext.set(entity.getLogId());
    
            logger.debug("IP为---->>> " + host + " <<<-----访问了系统");
            return true;
        }
    
        /**
         * 这个方法只会在当前这个Interceptor的preHandle方法返回值为true的时候才会执行。
         * postHandle是进行处理器拦截用的,它的执行时间是在处理器进行处理之 后, 也就是在Controller的方法调用之后执行,
         * 但是它会在DispatcherServlet进行视图的渲染之前执行,也就是说在这个方法中你可以对ModelAndView进行操作。
         * 这个方法的链式结构跟正常访问的方向是相反的,也就是说先声明的Interceptor拦截器该方法反而会后调用,
         * 这跟Struts2里面的拦截器的执行过程有点像,
         * 只是Struts2里面的intercept方法中要手动的调用ActionInvocation的invoke方法,
         * Struts2中调用ActionInvocation的invoke方法就是调用下一个Interceptor或者是调用action,
         * 然后要在Interceptor之前调用的内容都写在调用invoke之前,要在Interceptor之后调用的内容都写在调用invoke方法之后。
         */
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        }
    
        /**
         * 该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true时才会执行。
         * 该方法将在整个请求完成之后,也就是DispatcherServlet渲染了视图执行, 这个方法的主要作用是用于清理资源的,
         */
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
            String host = request.getRemoteHost();
            String logId = logContext.get();
            TLogEntity entity = logDao.findOne(logId);
            entity.setIsSuccess("Y");
            logDao.save(entity);
    
            logger.debug("IP为---->>> " + host + " <<<-----访问成功");
        }
    
    }

    4.  拦截器中的preHandle()与 postHandle()的运行顺序

  • 相关阅读:
    js 格式化时间
    js filter过滤数据
    vant 省市区三级联动 自定义json数据展示 取值
    移动端 table横向滚动
    js 判断字符串中是否包含某个字符串
    element ui form表单 刚进页面就验证
    js ES6 Promise.all 等两个接口都返回成功执行
    SDNU 1139.Emergency(起点更改最短路问题)
    SDNU 1062.Fibonacci(矩阵快速幂)
    SDNU 1103.买彩票(水题)
  • 原文地址:https://www.cnblogs.com/tjudzj/p/9204508.html
Copyright © 2011-2022 走看看