zoukankan      html  css  js  c++  java
  • Spring MVC中自定义拦截器的简单示例

    1. 引言

    拦截器(Interceptor)实现对每一个请求处理前后进行相关的业务处理,类似于Servlet的Filter。
    我们可以让普通的Bean实现HandlerIntercpetor接口或继承HandlerInterceptorAdapter类来实现自定义拦截器。

    通过重写WebMvcConfigurerAdapter的addIntercetors方法来注册一个计算每一次请求的处理时间的拦截器。

    2. 自定义拦截器的实现

    2.1 定义拦截器

    新建LogInterceptor类,并继承HandlerInterceptorAdapter类,重写preHandle、postHandle这两个方法。

    1. preHandle方法表示在请求发生前执行,内容如下:
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	request.setAttribute("begin", System.currentTimeMillis());
    	return true;
    }
    
    1. postHandle方法表示在请求完成后执行,内容如下:
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
    		ModelAndView modelAndView) throws Exception {
    	long begin = (long)request.getAttribute("begin");
    	request.removeAttribute("begin");
    	long end = System.currentTimeMillis();
    	System.out.println("本次请求消耗时间为:"+new Long(end-begin)+"ms");
    }
    

    2.2 配置拦截器

    2.2.1 使用xml配置

    1. 在配置文件中添加支持MVC的schema
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation=" http://www.springframework.org/schema/mvc  
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"
    
    1. 使用mvc:interceptors标签声明拦截器
    <mvc:interceptors>  
        <!-- 使用bean定义一个Interceptor,直接定义在mvc:interceptors根下面的Interceptor将拦截所有的请求 -->  
        <bean class="org.aming.demo.springmvc.interceptor.LogInterceptor"/>  
        <mvc:interceptor>  
            <mvc:mapping path="${指定的URL}"/>  
            <!-- 定义在mvc:interceptor下面的表示是对特定的请求才进行拦截的 -->  
            <bean class="${其他拦截器}"/>  
        </mvc:interceptor>  
    </mvc:interceptors>  
    

    说明:没有测试过!!!

    2.2.2 使用JavaConfig配置

    1. 配置拦截器的Bean
        @Bean
        public LogInterceptor logInterceptor() {
            return new LogInterceptor();
        }
    
    1. 重写addInterceptors方法,注册拦截器
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(logInterceptor());
        }
    

    说明:配置类需要继承WebMvcConfigurerAdapter类

    3. 运行结果

    运行结果

    4. 参考

    汪云飞:JavaEE开发的颠覆者:Spring Boot实战

  • 相关阅读:
    NOIP2018 模拟赛(二十二)雅礼NOI
    浅谈左偏树在OI中的应用
    HDU3062&&HDU1814
    2-SAT超入门讲解
    bitset常用用法&&简单题分析
    NOIp2014提高组初赛错题简析
    2018十月刷题列表
    BZOJ 4804: 欧拉心算
    Luogu P2568 GCD
    Luogu P4137 Rmq Problem / mex
  • 原文地址:https://www.cnblogs.com/xiao2/p/7412389.html
Copyright © 2011-2022 走看看