詳解DispatcherServlet

DispatcherServlet調用點方法

// 上層的調用方法為AbstractApplicationContext#refresh()---》onRefresh();
 @Override
    protected void onRefresh(ApplicationContext context) {
        initStrategies(context);
    }

    /**
     * 初始化解析器、映射器含长,適配器等等券腔,根據/org/springframework/web/servlet/DispatcherServlet.properties 配置文件初始化
     */
    protected void initStrategies(ApplicationContext context) {
        initMultipartResolver(context);
        initLocaleResolver(context);
        initThemeResolver(context);
        initHandlerMappings(context);
        initHandlerAdapters(context);
        initHandlerExceptionResolvers(context);
        initRequestToViewNameTranslator(context);
        initViewResolvers(context);
        initFlashMapManager(context);
    }

最主要的處理方法

doDispatch(HttpServletRequest request, HttpServletResponse response)

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpServletRequest processedRequest = request;
    HandlerExecutionChain mappedHandler = null;
    boolean multipartRequestParsed = false;

    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);

    try {
        ModelAndView mv = null;
        Exception dispatchException = null;

        try {
            processedRequest = checkMultipart(request);
            multipartRequestParsed = (processedRequest != request);

            // 1.為當前的請求匹配對應的處理Handler,其實也就是根據url去匹配要執(zhí)行Controller哪個方法.詳見 解釋1
            mappedHandler = getHandler(processedRequest);
            if (mappedHandler == null || mappedHandler.getHandler() == null) {
                noHandlerFound(processedRequest, response);
                return;
            }

            //2.確定當前請求的適配器
            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()) {
                    logger.debug("Last-Modified value for [" + getRequestUri(request) + "] is: " + lastModified);
                }
                if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
                    return;
                }
            }
// 3 前置通知器 HandlerInterceptor
            if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                return;
            }

            // 4.實際執(zhí)行
            mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

            if (asyncManager.isConcurrentHandlingStarted()) {
                return;
            }

            applyDefaultViewName(processedRequest, mv);
    //5. 后置過濾攔截
            mappedHandler.applyPostHandle(processedRequest, response, mv);
        }
        catch (Exception ex) {
            dispatchException = ex;
        }
        catch (Throwable err) {
            // As of 4.3, we're processing Errors thrown from handler methods as well,
            // making them available for @ExceptionHandler methods and other scenarios.
            dispatchException = new NestedServletException("Handler dispatch failed", err);
        }
//6.視圖渲染、返回值處理
        processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
    }
    catch (Exception ex) {
        triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
    }
    catch (Throwable err) {
        triggerAfterCompletion(processedRequest, response, mappedHandler,
                new NestedServletException("Handler processing failed", err));
    }
    finally {
        if (asyncManager.isConcurrentHandlingStarted()) {
            // Instead of postHandle and afterCompletion
            if (mappedHandler != null) {
            mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
            }
        }
        else {
            // Clean up any resources used by a multipart request.
            if (multipartRequestParsed) {
                cleanupMultipart(processedRequest);
            }
        }
    }
}
  1. 解釋1
    getHandler()-->AbstractHandlerMethodMapping#getHandlerInternal(HttpServletRequest request)拘泞。把HandlerMapping封裝成HandlerExecutionChain
@Override
    protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
        String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
        if (logger.isDebugEnabled()) {
            logger.debug("Looking up handler method for path " + lookupPath);
        }
        this.mappingRegistry.acquireReadLock();
        try {
            HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);
            if (logger.isDebugEnabled()) {
                if (handlerMethod != null) {
                    logger.debug("Returning handler method [" + handlerMethod + "]");
                }
                else {
                    logger.debug("Did not find handler method for [" + lookupPath + "]");
                }
            }
            return (handlerMethod != null ? handlerMethod.createWithResolvedBean() : null);
        }
        finally {
            this.mappingRegistry.releaseReadLock();
        }
    }

** url 映射method在容器初始化的時候已經準備好**

// 入口 開始聲明的initStrategies() -->initHandlerMappings(context);會山路十八彎的調到
AbstractHandlerMethodMapping#initHandlerMethods() {
    if (beanType != null && isHandler(beanType)) {
      detectHandlerMethods(beanName);
    }
}
-- isHandler(beanType)判斷是否有@Controller || @RequestMapping注解
//detectHandlerMethods 方法內
Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
new MethodIntrospector.MetadataLookup<T>() {
    @Override
    public T inspect(Method method) {
        try {
            return getMappingForMethod(method, userType);
        }
        catch (Throwable ex) {
            throw new IllegalStateException("Invalid mapping on handler class [" +
                    userType.getName() + "]: " + method, ex);
        }
    }
});
// 執(zhí)行完上述方法之后methods 纷纫,Controller內帶有RequestMapping的method為key, @RequestMapping封裝成RequestMappingInfo為value

Map<Method, T> methods =
{
    public java.lang.String ren.xuedao.moudle.sys.controller.LoginController.login(java.lang.String,java.lang.String,org.springframework.ui.Model)={[/login],methods=[POST]}
    , public java.lang.String ren.xuedao.moudle.sys.controller.LoginController.home(org.springframework.ui.Model)={[/home],methods=[GET]}, 
    public java.lang.String ren.xuedao.moudle.sys.controller.LoginController.logOut()={[/logout]}, 
    public java.lang.String ren.xuedao.moudle.sys.controller.LoginController.layui()={[/layui]}
}
// 循環(huán)methods Map 構造另一種形式的map
for (Map.Entry<Method, T> entry : methods.entrySet()) {
    Method invocableMethod = AopUtils.selectInvocableMethod(entry.getKey(), userType);
    T mapping = entry.getValue();
    registerHandlerMethod(handler, invocableMethod, mapping);
}

public void register(T mapping, Object handler, Method method) {
    this.readWriteLock.writeLock().lock();
    try {
        HandlerMethod handlerMethod = createHandlerMethod(handler, method);
        assertUniqueMethodMapping(handlerMethod, mapping);

        if (logger.isInfoEnabled()) {
            logger.info("Mapped \"" + mapping + "\" onto " + handlerMethod);
        }
        this.mappingLookup.put(mapping, handlerMethod);

        List<String> directUrls = getDirectUrls(mapping);
        for (String url : directUrls) {
            this.urlLookup.add(url, mapping);
        }

        String name = null;
        if (getNamingStrategy() != null) {
            name = getNamingStrategy().getName(handlerMethod, mapping);
            addMappingName(name, handlerMethod);
        }

        CorsConfiguration corsConfig = initCorsConfiguration(handler, method, mapping);
        if (corsConfig != null) {
            this.corsLookup.put(handlerMethod, corsConfig);
        }
        // 添加到registry
        this.registry.put(mapping, new MappingRegistration<T>(mapping, handlerMethod, directUrls, name));
    }
    finally {
        this.readWriteLock.writeLock().unlock();
    }
}

// 最終模樣
Map<T, MappingRegistration<T>> registry = 
{
    {[/login],methods=[POST]}=org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistration@81e87eb
    , {[/home],methods=[GET]}=org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistration@6bb30dc5
}

AbstractHandlerMethodMapping$MappingRegistration {
    directUrls = [/login],
    handlerMethod = public java.lang.String ren.xuedao.moudle.sys.controller.LoginController.login(java.lang.String,java.lang.String,org.springframework.ui.Model),
    mapping = {[/login],methods=[POST]},
    mappingName = LC#login
}
  1. HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());用到了策略模式去匹配對應的
    HandlerAdapter一共有三種,即下圖所示陪腌。作用就是去使用哪一種類型去處理請求辱魁。下面4中所示。


    Jietu20171017-214227@2x.jpg
  2. 前置過濾器攔截

if (!mappedHandler.applyPreHandle(processedRequest, response)) {
      return;
}
  1. 實際執(zhí)行
    mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
    ServletInvocableHandlerMethod#invokeAndHandle
    4.1 調用 InvocableHandlerMethod#invokeForRequest
    4.1.1Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);InvocableHandlerMethod.getMethodArgumentValues(request, mavContainer, providedArgs);策略模式獲取hand中方法的入參數(shù)組
    4.1.2 Object returnValue = doInvoke(args); 反射調用hand中的method
    4.2 調用this.returnValueHandlers.handleReturnValue(
    returnValue, getReturnValueType(returnValue), mavContainer, webRequest);對method的返回參數(shù)進行處理诗鸭,也是策略模式染簇。
  2. 后置過濾攔截器 mappedHandler.applyPostHandle(processedRequest, response, mv);
  3. processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);視圖渲染、返回值處理
    6.1 render(mv, request, response);
    6.2 mappedHandler.triggerAfterCompletion(request, response, null);后置過濾器强岸,釋放資源锻弓,關閉連接
    ---未完待續(xù) ,后續(xù)把圖補上。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末蝌箍,一起剝皮案震驚了整個濱河市青灼,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌十绑,老刑警劉巖聚至,帶你破解...
    沈念sama閱讀 211,194評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異本橙,居然都是意外死亡扳躬,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,058評論 2 385
  • 文/潘曉璐 我一進店門甚亭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來贷币,“玉大人,你說我怎么就攤上這事亏狰∫畚疲” “怎么了?”我有些...
    開封第一講書人閱讀 156,780評論 0 346
  • 文/不壞的土叔 我叫張陵暇唾,是天一觀的道長促脉。 經常有香客問我辰斋,道長,這世上最難降的妖魔是什么瘸味? 我笑而不...
    開封第一講書人閱讀 56,388評論 1 283
  • 正文 為了忘掉前任宫仗,我火速辦了婚禮,結果婚禮上旁仿,老公的妹妹穿的比我還像新娘藕夫。我一直安慰自己,他們只是感情好枯冈,可當我...
    茶點故事閱讀 65,430評論 5 384
  • 文/花漫 我一把揭開白布毅贮。 她就那樣靜靜地躺著,像睡著了一般尘奏。 火紅的嫁衣襯著肌膚如雪滩褥。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,764評論 1 290
  • 那天罪既,我揣著相機與錄音铸题,去河邊找鬼。 笑死琢感,一個胖子當著我的面吹牛,可吹牛的內容都是我干的探熔。 我是一名探鬼主播驹针,決...
    沈念sama閱讀 38,907評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼诀艰!你這毒婦竟也來了柬甥?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 37,679評論 0 266
  • 序言:老撾萬榮一對情侶失蹤其垄,失蹤者是張志新(化名)和其女友劉穎苛蒲,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體绿满,經...
    沈念sama閱讀 44,122評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡臂外,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,459評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了喇颁。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片漏健。...
    茶點故事閱讀 38,605評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖橘霎,靈堂內的尸體忽然破棺而出蔫浆,到底是詐尸還是另有隱情,我是刑警寧澤姐叁,帶...
    沈念sama閱讀 34,270評論 4 329
  • 正文 年R本政府宣布瓦盛,位于F島的核電站洗显,受9級特大地震影響,放射性物質發(fā)生泄漏原环。R本人自食惡果不足惜墙懂,卻給世界環(huán)境...
    茶點故事閱讀 39,867評論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望扮念。 院中可真熱鬧损搬,春花似錦、人聲如沸柜与。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,734評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽弄匕。三九已至颅悉,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間迁匠,已是汗流浹背剩瓶。 一陣腳步聲響...
    開封第一講書人閱讀 31,961評論 1 265
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留城丧,地道東北人延曙。 一個月前我還...
    沈念sama閱讀 46,297評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像亡哄,于是被迫代替她去往敵國和親枝缔。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 43,472評論 2 348

推薦閱讀更多精彩內容