SpringMVC-Interceptor

Spring-MVC的拦截器HandlerInterceptor总接口。

什么是Spring-MVC的拦截器

实现一个HandlerInterceptor拦截器可以直接实现HandlerInterceptor接口,也可以继承HandlerInterceptorAdapter类。这两种方法殊途同归.

1
2
3
4
5
6
7
8
9
10
11
12
public boolean preHandle(HttpServletRequest request, HttpServletResponse response
, Object handler) throws Exception {
return true;
}

public void postHandle(HttpServletRequest request, HttpServletResponse response
, Object handler, ModelAndView modelAndView) throws Exception {
}

public void afterCompletion(HttpServletRequest request, HttpServletResponse response
, Object handler, Exception ex) throws Exception {
}

分别实现预处理、后处理(调用了Service并返回ModelAndView,但未进行页面渲染)、返回处理(已经渲染了页面)

  • 在preHandle中,可以进行编码、安全控制等处理;
  • 在postHandle中,有机会修改ModelAndView;
  • 在afterCompletion中,可以根据ex是否为null判断是否发生了异常,进行日志记录。

实现一个Spring-MVC的拦截器

Demo: 我们假设UserController中的注册操作只在9:00-12:00开放,那么就可以使用拦截器实现这个功能。

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
public class TimeBasedAccessInterceptor extends HandlerInterceptorAdapter {    
private int openingTime;
private int closingTime;
private String mappingURL;//利用正则映射到需要拦截的路径
public void setOpeningTime(int openingTime) {
this.openingTime = openingTime;
}
public void setClosingTime(int closingTime) {
this.closingTime = closingTime;
}
public void setMappingURL(String mappingURL) {
this.mappingURL = mappingURL;
}
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
String url=request.getRequestURL().toString();
if(mappingURL==null || url.matches(mappingURL)){
Calendar c=Calendar.getInstance();
c.setTime(new Date());
int now=c.get(Calendar.HOUR_OF_DAY);
if(now<openingTime || now>closingTime){
request.setAttribute("msg", "注册开放时间:9:00-12:00");
request.getRequestDispatcher("/msg.jsp").forward(request, response);
return false;
}
return true;
}
return true;
}
}

基于注解风格的Spring-MVC的拦截器

1
2
3
4
5
6
7
< bean class = "org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" >   
     < property name = "interceptors" >   
         <list>   
                <bean class = "packageName.XXXInterceptor"/>   
         </ list >   
     </ property >   
</ bean >

拦截器的工作过程

当客户端发送请求后,DispatcherServlet.doDispatch方法中会处理请求,封装了springMVC处理请求的整个过程

下面贴出doDispatch(req, res)中与拦截器相关的代码:

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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
int interceptorIndex = -1;

try {
ModelAndView mv;
boolean errorView = false;

try {
processedRequest = checkMultipart(request);

// 根据请求获取其handler
// handlerMapping解析url得到的controller信息
mappedHandler = getHandler(processedRequest, false);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(processedRequest, response);
return;
}

// handleradapter是根据handlerMapping解析而来的controller信息去调用controller
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

// Process last-modified header, if supported by the handler.
String method = request.getMethod();
boolean isGet = "GET".equals(method);
if (isGet || "HEAD".equals(method)) {
long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
if (logger.isDebugEnabled()) {
String requestUri = urlPathHelper.getRequestUri(request);
logger.debug("Last-Modified value for [" + requestUri + "] is: " + lastModified);
}
if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
return;
}
}

// 调用拦截器的preHandle们 --> 预处理
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = 0; i < interceptors.length; i++) {
HandlerInterceptor interceptor = interceptors[i];
if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) {
triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
return;
}
interceptorIndex = i;
}
}

// controller实际执行
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

// Do we need view name translation?
if (mv != null && !mv.hasView()) {
mv.setViewName(getDefaultViewName(request));
}

// 调用拦截器的postHandle们 --> 后处理
if (interceptors != null) {
for (int i = interceptors.length - 1; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv);
}
}
}
catch (ModelAndViewDefiningException ex) {
logger.debug("ModelAndViewDefiningException encountered", ex);
mv = ex.getModelAndView();
}
catch (Exception ex) {
Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
mv = processHandlerException(processedRequest, response, handler, ex);
errorView = (mv != null);
}

// Did the handler return a view to render?
if (mv != null && !mv.wasCleared()) {
render(mv, processedRequest, response);
if (errorView) {
WebUtils.clearErrorRequestAttributes(request);
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Null ModelAndView returned to DispatcherServlet with name '" + getServletName() +
"': assuming HandlerAdapter completed request handling");
}
}

// 反向调用after-completion --> 返回处理
triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
}

catch (Exception ex) {
// 反向调用after-completion --> 返回处理for thrown exception.
triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
throw ex;
}
catch (Error err) {
ServletException ex = new NestedServletException("Handler processing failed", err);
// 反向调用after-completion --> 返回处理for thrown exception.
triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
throw ex;
}

finally {
// Clean up any resources used by a multipart request.
if (processedRequest != request) {
cleanupMultipart(processedRequest);
}
}
}

参考阅读

Donate here.