背景
日常coding中,要解決項(xiàng)目當(dāng)中遇到的問題榜田,難免會(huì)需要寫一個(gè)Converter益兄,aspect,或者擴(kuò)展一個(gè)MediaType等等箭券。這時(shí)候需要寫一個(gè)侵入性小的擴(kuò)展净捅,就需要了解源碼。我找了很多博客文章邦鲫,甚至看了《看透Spring MVC:源代碼分析與實(shí)踐》灸叼,寫的很好神汹,但是視角都是從整體框架出發(fā)庆捺,大而全,而我僅僅只是想解決當(dāng)前的問題屁魏,所以我以代碼跟蹤的視角記錄下這篇文章滔以,免得下次忘了還要重新跟蹤源碼,直接過來看就好了氓拼。
目的
從源碼中提取可能用到的工具你画,特別是標(biāo)注好注意事項(xiàng),下次擴(kuò)展可以查閱桃漾。
準(zhǔn)備
- springboot 2.1.1.RELEASE的demo
- pom依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 示例類Employee坏匪,省略getter/setter
public class Employee {
private Long id;
private String name;
private Integer age;
private Date birthday;
private Date createTime;
}
- Controller示例類
@RestController
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@PostMapping("/employee")
public ResponseEntity<Employee> insert(Employee employee){
employee.setId(1L);
employee.setCreateTime(new Date());
return ResponseEntity.ok(employee);
}
}
斷點(diǎn)
如圖上斷點(diǎn)
請求參數(shù)如圖
ALT+左鍵點(diǎn)擊employee檢查參數(shù)
FrameworkServlet
- 我們在Debugger視圖的Frames里從底部往上,找到第一個(gè)屬于spring-webmvc包的類撬统,FrameworkServlet
- 通過查看源碼适滓,我們GET到第一個(gè)工具類,HttpMethod恋追,這個(gè)枚舉類包含了所有的http方法凭迹。
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpMethod httpMethod = HttpMethod.resolve(request.getMethod());
if (httpMethod == HttpMethod.PATCH || httpMethod == null) {
processRequest(request, response);
}
else {
super.service(request, response);
}
}
- 在Frames視圖繼續(xù)向上推,可以發(fā)現(xiàn)從 HttpServlet 轉(zhuǎn)了一遭到了 FrameworkServlet.doPost 苦囱,然后來到了 FrameworkServlet.processRequest (刪減版)
protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// (1)
LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
LocaleContext localeContext = buildLocaleContext(request);
RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
initContextHolders(request, localeContext, requestAttributes);
try {
// (2)
doService(request, response);
}
catch (ServletException | IOException ex) {
}
catch (Throwable ex) {
}
finally {
resetContextHolders(request, previousLocaleContext, previousAttributes);
if (requestAttributes != null) {
requestAttributes.requestCompleted();
}
// (3)
publishRequestHandledEvent(request, response, startTime, failureCause);
}
}
看得出來嗅绸,做了三件事
- ContextHolder的設(shè)置和重置
具體見:源碼跟蹤-springmvc(二):LocaleContextHolder和RequestContextHolder - 執(zhí)行
doService
方法,也是真正執(zhí)行handler
的方法撕彤。 - 執(zhí)行了
publishRequestHandledEvent
鱼鸠,代碼如下
private void publishRequestHandledEvent(HttpServletRequest request, HttpServletResponse response,
long startTime, @Nullable Throwable failureCause) {
if (this.publishEvents && this.webApplicationContext != null) {
// Whether or not we succeeded, publish an event.
long processingTime = System.currentTimeMillis() - startTime;
this.webApplicationContext.publishEvent(
new ServletRequestHandledEvent(this,
request.getRequestURI(), request.getRemoteAddr(),
request.getMethod(), getServletConfig().getServletName(),
WebUtils.getSessionId(request), getUsernameForRequest(request),
processingTime, failureCause, response.getStatus()));
}
}
我們知道webApplicationContext
繼承了ApplicationEventPublisher
,擁有了發(fā)布事件的能力羹铅,我把發(fā)布的事件打印出來看一下
@EventListener
public void printServletRequestHandledEvent(ServletRequestHandledEvent event){
System.out.println(event);
}
打印結(jié)果如下
ServletRequestHandledEvent: url=[/employee]; client=[127.0.0.1]; method=[POST]; servlet=[dispatcherServlet]; session=[null]; user=[null]; time=[52ms]; status=[OK]
如果發(fā)現(xiàn)打印的內(nèi)容滿足需要蚀狰,我們就不需要再寫個(gè)aop用來記錄日志啦。
DispatcherSevlet
- 現(xiàn)在進(jìn)入了DispatcherSevlet.doService方法(刪減版)
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> attributesSnapshot = null;
if (WebUtils.isIncludeRequest(request)) {
attributesSnapshot = new HashMap<>();
Enumeration<?> attrNames = request.getAttributeNames();
while (attrNames.hasMoreElements()) {
String attrName = (String) attrNames.nextElement();
if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) {
attributesSnapshot.put(attrName, request.getAttribute(attrName));
}
}
}
request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
try {
doDispatch(request, response);
}
finally {
if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
// Restore the original attribute snapshot, in case of an include.
if (attributesSnapshot != null) {
restoreAttributesAfterInclude(request, attributesSnapshot);
}
}
}
}
這里有兩件事
- 如果滿足一定的條件(
WebUtils.isIncludeRequest(request)
)睦裳,會(huì)把request的attributes做一份快照備份(attributesSnapshot
)造锅,執(zhí)行完handler后還原備份(restoreAttributesAfterInclude(request, attributesSnapshot)
)。但是這里如果沒有成立廉邑,也就沒有執(zhí)行哥蔚,就先不管倒谷。但是很明顯,這個(gè)手法和上面的ContextHolder如出一轍糙箍。這時(shí)候其實(shí)能夠象出來渤愁,這樣做的目的是為了安全。 - 在request中設(shè)置了一堆的attributes深夯,有一個(gè)特別顯眼抖格,
request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
,這個(gè)時(shí)候我們又get到一個(gè)獲取webApplicationContext
的辦法咕晋。
WebApplicationContext wac = (WebApplicationContext) request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);
- 進(jìn)入了DispatcherSevlet.doDispatch方法(刪減版)
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
// ....
try {
//...
try {
// (1)
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(processedRequest, response);
return;
}
// (2)
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
// (3)
String method = request.getMethod();
boolean isGet = "GET".equals(method);
if (isGet || "HEAD".equals(method)) {
long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
if (logger.isDebugEnabled()) {
logger.debug("Last-Modified value for [" + getRequestUri(request) + "] is: " + lastModified);
}
if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
return;
}
}
// (4)
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// (5)
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
// (6)
mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exception ex) {
dispatchException = ex;
}
catch (Throwable err) {
dispatchException = new NestedServletException("Handler dispatch failed", err);
}
// (7)
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
catch (Exception ex) {
// (7)
triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
}
catch (Throwable err) {
// (7)
triggerAfterCompletion(processedRequest, response, mappedHandler,
new NestedServletException("Handler processing failed", err));
}
}
這里非常重要了雹拄,對(duì)應(yīng)代碼中的注釋,解釋如下
- 獲取到mappedHandler掌呜,其實(shí)也就HandlerExecutionChain
具體見源碼跟蹤-springmvc(三):RequestMappingHandlerMapping - 獲取處理器適配器滓玖,就是RequestMappingHandlerAdapter
- http協(xié)議中的緩存實(shí)現(xiàn),可以看Spring mvc HTTP協(xié)議之緩存機(jī)制
- 分別調(diào)用mappedHandler中的三個(gè)攔截器的preHandle方法
- 執(zhí)行真正的handler
具體見:源碼跟蹤-springmvc(四):RequestMappingHandlerAdapter - 執(zhí)行攔截器的postHandle方法
- 執(zhí)行攔截器的afterCompletion方法