1. 引言
拦截器(Interceptor)实现对每一个请求处理前后进行相关的业务处理,类似于Servlet的Filter。
我们可以让普通的Bean实现HandlerIntercpetor接口或继承handlerinterceptorAdapter类来实现自定义拦截器。
通过重写WebMvcConfigurerAdapter的addIntercetors方法来注册一个计算每一次请求的处理时间的拦截器。
2. 自定义拦截器的实现
2.1 定义拦截器
新建LogInterceptor类,并继承handlerinterceptorAdapter类,重写preHandle、postHandle这两个方法。
public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception {
request.setAttribute("begin",System.currentTimeMillis());
return true;
}
@Override
public void postHandle(HttpServletRequest request,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配置
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"
<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配置
- 配置拦截器的Bean
@Bean
public LogInterceptor logInterceptor() {
return new LogInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(logInterceptor());
}
说明:配置类需要继承WebMvcConfigurerAdapter类
3. 运行结果
4. 参考
汪云飞:JavaEE开发的颠覆者:Spring Boot实战
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。