源碼跟蹤-springmvc(一):DispatcherSevlet

背景

日常coding中,要解決項(xiàng)目當(dāng)中遇到的問題,難免會需要寫一個(gè)Converter,aspect,或者擴(kuò)展一個(gè)MediaType等等。這時(shí)候需要寫一個(gè)侵入性小的擴(kuò)展,就需要了解源碼。我找了很多博客文章,甚至看了《看透Spring MVC:源代碼分析與實(shí)踐》,寫的很好,但是視角都是從整體框架出發(fā),大而全,而我僅僅只是想解決當(dāng)前的問題,所以我以代碼跟蹤的視角記錄下這篇文章,免得下次忘了還要重新跟蹤源碼,直接過來看就好了。

目的

從源碼中提取可能用到的工具,特別是標(biāo)注好注意事項(xiàng),下次擴(kuò)展可以查閱。

準(zhǔn)備

  1. springboot 2.1.1.RELEASE的demo
  2. 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>
  1. 示例類Employee,省略getter/setter
public class Employee {

    private Long id;
    private String name;
    private Integer age;
    private Date birthday;
    private Date createTime;
}
  1. 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

  1. 我們在Debugger視圖的Frames里從底部往上,找到第一個(gè)屬于spring-webmvc包的類,FrameworkServlet
  2. 通過查看源碼,我們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);
        }
    }
  1. 在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);
        }
    }

看得出來,做了三件事

  1. ContextHolder的設(shè)置和重置
    具體見:源碼跟蹤-springmvc(二):LocaleContextHolder和RequestContextHolder
  2. 執(zhí)行doService方法,也是真正執(zhí)行handler的方法。
  3. 執(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

  1. 現(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);
                }
            }
        }
    }

這里有兩件事

  1. 如果滿足一定的條件(WebUtils.isIncludeRequest(request)),會把request的attributes做一份快照備份(attributesSnapshot),執(zhí)行完handler后還原備份(restoreAttributesAfterInclude(request, attributesSnapshot))。但是這里如果沒有成立,也就沒有執(zhí)行,就先不管。但是很明顯,這個(gè)手法和上面的ContextHolder如出一轍。這時(shí)候其實(shí)能夠象出來,這樣做的目的是為了安全。
  2. 在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);
  1. 進(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));
        }
    }

這里非常重要了,對應(yīng)代碼中的注釋,解釋如下

  1. 獲取到mappedHandler,其實(shí)也就HandlerExecutionChain
    具體見源碼跟蹤-springmvc(三):RequestMappingHandlerMapping
  2. 獲取處理器適配器,就是RequestMappingHandlerAdapter
  3. http協(xié)議中的緩存實(shí)現(xiàn),可以看Spring mvc HTTP協(xié)議之緩存機(jī)制
  4. 分別調(diào)用mappedHandler中的三個(gè)攔截器的preHandle方法
  5. 執(zhí)行真正的handler
    具體見:源碼跟蹤-springmvc(四):RequestMappingHandlerAdapter
  6. 執(zhí)行攔截器的postHandle方法
  7. 執(zhí)行攔截器的afterCompletion方法
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容