springMvc請(qǐng)求如何獲取相關(guān)HandlerMapping(四)


github原文鏈接 https://github.com/DespairYoke/java-advance颖系。創(chuàng)作不易嗅剖,請(qǐng)給個(gè)免費(fèi)的star,已表支持嘁扼。

在Servlet如何關(guān)聯(lián)spring中信粮,說過當(dāng)請(qǐng)求來后會(huì)被轉(zhuǎn)發(fā)到springDispatcherServlet類中的doService方法。

@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
   doDispatch(request, response);
}

轉(zhuǎn)發(fā)到doDispatch中

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
    mappedHandler = getHandler(processedRequest);
}

getHandler獲取相關(guān)

protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
    if (this.handlerMappings != null) {
        for (MyHandlerMapping hm : this.handlerMappings) {
            if (logger.isTraceEnabled()) {
                logger.trace(
                        "Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'");
            }
            HandlerExecutionChain handler = hm.getHandler(request);
            if (handler != null) {
                return handler;
            }
        }
    }
    return null;
}

可以看出趁啸,循環(huán)遍歷初始化時(shí)加載的handlerMappings蒋院。在初始化時(shí)加載是BeanNameUrlHandlerMappingRequestMappingHandlerMapping(不知道的,可以參考上篇文章spingMvc初始HandlerMapping)莲绰。
BeanNameUrlHandlerMapping不滿條件返回null欺旧,而RequestMappingHandlerMapping滿足條件,通過getHandler返回我們想要的HandlerExecutionChain蛤签。

public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
    Object handler = getHandlerInternal(request);

    HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
    return executionChain;
}

getHandlerExecutionChain可見是對(duì)handler和request的封裝辞友,真正的處理還是如何獲取到這個(gè)handler
具體代碼寫在了AbstractHandlerMethodMapping

protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
    String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);

    this.mappingRegistry.acquireReadLock();
    try {
        HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);
        }
        return (handlerMethod != null ? handlerMethod.createWithResolvedBean() : null);
    }
    finally {
        this.mappingRegistry.releaseReadLock();
    }
}

在前文分析中震肮,handlerMethod在初始化的時(shí)候放在了称龙,mappingRegistry中,由上述代碼戳晌,可以看出是從mappingRegistry中鲫尊,匹配請(qǐng)求,并返回handlerMethod沦偎。
那我們看下lookupHandlerMethod方法吧疫向。

protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
    List<Match> matches = new ArrayList<>();
    List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);
    if (directPathMatches != null) {
        addMatchingMappings(directPathMatches, matches, request);
    }
    if (matches.isEmpty()) {
        // No choice but to go through all mappings...
        addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, request);
    }

    if (!matches.isEmpty()) {
        Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
        matches.sort(comparator);
        if (logger.isTraceEnabled()) {
            logger.trace("Found " + matches.size() + " matching mapping(s) for [" + lookupPath + "] : " + matches);
        }
        Match bestMatch = matches.get(0);
        if (matches.size() > 1) {
            if (CorsUtils.isPreFlightRequest(request)) {
                return PREFLIGHT_AMBIGUOUS_MATCH;
            }
            Match secondBestMatch = matches.get(1);
            if (comparator.compare(bestMatch, secondBestMatch) == 0) {
                Method m1 = bestMatch.handlerMethod.getMethod();
                Method m2 = secondBestMatch.handlerMethod.getMethod();
                throw new IllegalStateException("Ambiguous handler methods mapped for HTTP path '" +
                        request.getRequestURL() + "': {" + m1 + ", " + m2 + "}");
            }
        }
        handleMatch(bestMatch.mapping, lookupPath, request);
        return bestMatch.handlerMethod;
    }
    else {
        return handleNoMatch(this.mappingRegistry.getMappings().keySet(), lookupPath, request);
    }
}

果不其然是對(duì)我們的請(qǐng)求路徑進(jìn)行最佳匹配
這樣我們就回去到初始化handlerMapping時(shí)生成的handlerMethod豪嚎,為后續(xù)handlerAdapter做好參數(shù)準(zhǔn)備搔驼。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市侈询,隨后出現(xiàn)的幾起案子舌涨,更是在濱河造成了極大的恐慌,老刑警劉巖扔字,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件囊嘉,死亡現(xiàn)場(chǎng)離奇詭異温技,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)扭粱,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門舵鳞,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人焊刹,你說我怎么就攤上這事系任。” “怎么了虐块?”我有些...
    開封第一講書人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵俩滥,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我贺奠,道長(zhǎng)霜旧,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任儡率,我火速辦了婚禮挂据,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘儿普。我一直安慰自己崎逃,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開白布眉孩。 她就那樣靜靜地躺著个绍,像睡著了一般。 火紅的嫁衣襯著肌膚如雪浪汪。 梳的紋絲不亂的頭發(fā)上巴柿,一...
    開封第一講書人閱讀 51,292評(píng)論 1 301
  • 那天,我揣著相機(jī)與錄音死遭,去河邊找鬼广恢。 笑死,一個(gè)胖子當(dāng)著我的面吹牛呀潭,可吹牛的內(nèi)容都是我干的钉迷。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼蜗侈,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼篷牌!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起踏幻,我...
    開封第一講書人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎戳杀,沒想到半個(gè)月后该面,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體夭苗,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年隔缀,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了题造。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡猾瘸,死狀恐怖界赔,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情牵触,我是刑警寧澤淮悼,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站揽思,受9級(jí)特大地震影響袜腥,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜钉汗,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一羹令、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧损痰,春花似錦福侈、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至尝丐,卻和暖如春显拜,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背爹袁。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來泰國打工远荠, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人失息。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓譬淳,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國和親盹兢。 傳聞我的和親對(duì)象是個(gè)殘疾皇子邻梆,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354

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