软件编程
位置:首页>> 软件编程>> java编程>> Spring MVC中自定义 * 的实例讲解

Spring MVC中自定义 * 的实例讲解

作者:jingxian  发布时间:2023-12-19 05:09:04 

标签:自定义, , ,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;
}

2.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"

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配置

3.配置 * 的Bean


@Bean
public LogInterceptor logInterceptor() {
return new LogInterceptor();
}

4.重写addInterceptors方法,注册 *


@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(logInterceptor());
}

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

3. 运行结果

Spring MVC中自定义 * 的实例讲解

来源:http://www.cnblogs.com/xiao2/p/7412389.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com