源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Spring MVC中自定义拦截器的实例讲解

  • 时间:2021-12-26 00:02 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Spring MVC中自定义拦截器的实例讲解
[b]1. 引言[/b] 拦截器(Interceptor)实现对每一个请求处理前后进行相关的业务处理,类似于Servlet的Filter。 我们可以让普通的Bean实现HandlerIntercpetor接口或继承HandlerInterceptorAdapter类来实现自定义拦截器。 通过重写WebMvcConfigurerAdapter的addIntercetors方法来注册一个计算每一次请求的处理时间的拦截器。 [b]2. 自定义拦截器的实现[/b] [b]2.1 定义拦截器[/b] 新建LogInterceptor类,并继承HandlerInterceptorAdapter类,重写preHandle、postHandle这两个方法。 [b]1.preHandle方法表示在请求发生前执行,内容如下:[/b]
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
request.setAttribute("begin", System.currentTimeMillis());
return true;
}

[b]2.postHandle方法表示在请求完成后执行,内容如下:[/b]
@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");
}

[b]2.2 配置拦截器[/b] [b]2.2.1 使用xml配置[/b] 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"

2.使用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配置 [b]3.配置拦截器的Bean[/b]
@Bean
public LogInterceptor logInterceptor() {
 return new LogInterceptor();
}

[b]4.重写addInterceptors方法,注册拦截器[/b]
@Override
public void addInterceptors(InterceptorRegistry registry) {
 registry.addInterceptor(logInterceptor());
}

说明:配置类需要继承WebMvcConfigurerAdapter类 [b]3. 运行结果[/b] [img]http://files.jb51.net/file_images/article/201708/201708230912042.png[/img] 以上这篇Spring MVC中自定义拦截器的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部