spring mvc
原理真的必须懂, 之前写的源码导读。
DispatcherServlet
源码位置: org.springframework.web.servlet.DispatcherServlet#doDispatch
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
| protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
...
try {
...
try {
// 检查是否为文件上传
processedRequest = checkMultipart(request);
// 获取 HandlerMapping
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null) {
// 40
noHandlerFound(processedRequest, response);
return;
}
// 获取 HandlerAdapter
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
...
// 执行 HandlerInterceptor#preHandle
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// 执行请求
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
...
// 执行 HandlerInterceptor#postHandle
mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exception ex) {
dispatchException = ex;
}
catch (Throwable err) {
dispatchException = new NestedServletException("Handler dispatch failed", err);
}
// 处理异常,然后执行 HandlerInterceptor#afterCompletion
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
catch (Exception ex) {
// 执行 HandlerInterceptor#afterCompletion
triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
}
catch (Throwable err) {
// 执行 HandlerInterceptor#afterCompletion
triggerAfterCompletion(processedRequest, response, mappedHandler,
new NestedServletException("Handler processing failed", err));
}
finally {
...
}
}
|
总结:
- 根据 url 查找对应的 HandlerMapping。
- 根据 HandlerMapping 查找对应的 HandlerAdapter。
- 执行 HandlerInterceptor#preHandle。
- 执行请求。
- 执行 HandlerInterceptor#postHandle。
- 执行 HandlerExceptionResolver#resolveException。
- 执行 HandlerInterceptor#afterCompletion。
HandlerMapping
常用实现类 RequestMappingHandlerMapping
HandlerAdapter
常用实现类 RequestMappingHandlerAdapter