使用HandlerInterceptor拦截器,可以拦截请求,实现通用的日志管理操作
一、添加拦截器类
在"src/main/java"代码文件夹的"org.xs.demo1"的包下新建"LogInterceptor.java"类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
package org.xs.demo1;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* 日志拦截器
* @author ThinkGem
*/
public class LogInterceptor implements HandlerInterceptor {
private final Logger log = LoggerFactory.getLogger(getClass().getName());
private static final ThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>( "ThreadLocal StartTime" );
/**
* 预处理
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
long beginTime = System.currentTimeMillis(); //开始时间
startTimeThreadLocal.set(beginTime); //线程绑定变量(该数据只有当前请求的线程可见)
log.info( "开始计时: {}" , new SimpleDateFormat( "hh:mm:ss.SSS" ).format(beginTime));
return true ;
}
/**
* 返回处理
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if (modelAndView != null ){
log.info( "ViewName: " + modelAndView.getViewName());
}
}
/**
* 后处理
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 保存日志
//LogUtils.saveLog(request, handler, ex, null);
// 输出日志信息
log.info( "访问地址:" + request.getRequestURI() + ",执行方式:" + request.getMethod());
long beginTime = startTimeThreadLocal.get(); //得到线程绑定的局部变量(开始时间)
long endTime = System.currentTimeMillis(); //结束时间
log.info( "计时结束:{}" , new SimpleDateFormat( "hh:mm:ss.SSS" ).format(endTime));
}
}
|
二、修改配置文件
修改spring-mvc.xml件,加入:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<!-- 拦截器配置 -->
< mvc:interceptors >
< mvc:interceptor >
< mvc:mapping path = "/**" />
< bean class = "org.xs.demo1.LogInterceptor" />
</ mvc:interceptor >
</ mvc:interceptors >
|
三、运行测试
访问"http://localhost:8080/demo1/hello/list2"地址
可以看到拦截器中输出的日志信息了
实例代码地址:spring-HandlerInterceptor.rar
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/ctxsdhy/p/6421067.html