首先更正一個錯誤葬荷,在上節(jié)中我們講過doMatch中的matchStrings方法會在后面在handlerAdapter處理時還會調(diào)用一次這個方法角塑,在這個方法里面會解析url參數(shù)并將其綁定在request中毁靶。實(shí)際上這個操作是在getHandler的時候進(jìn)行的,在得到最佳匹配mapping之后會執(zhí)行handleMatch(bestMatch.mapping, lookupPath, request)方法將mapping和request綁定。這里RequestMappingInfoHandlerMapping重寫了handleMath方法。我們一起來看看
protected void handleMatch(RequestMappingInfo info, String lookupPath, HttpServletRequest request) {
// 首先還是調(diào)用父類方法綁定mapping
super.handleMatch(info, lookupPath, request);
String bestPattern;
Map<String, String> uriVariables;
Set<String> patterns = info.getPatternsCondition().getPatterns();
if (patterns.isEmpty()) {
bestPattern = lookupPath;
uriVariables = Collections.emptyMap();
} else {
// 這里會根據(jù)pattern重新獲取url中的參數(shù)
bestPattern = patterns.iterator().next();
uriVariables = getPathMatcher().extractUriTemplateVariables(bestPattern, lookupPath);
}
request.setAttribute(BEST_MATCHING_PATTERN_ATTRIBUTE, bestPattern);
// 將得到的參數(shù)decode坛怪,以免前臺傳參encode導(dǎo)致亂碼
Map<String, String> decodedUriVariables = getUrlPathHelper().decodePathVariables(request, uriVariables);
// 注意。這里就將參數(shù)綁定在了request中股囊,后面Adapter調(diào)用時直接從這里取袜匿,取不到會報錯
request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, decodedUriVariables);
}
public boolean matchStrings(String str, @Nullable Map<String, String> uriTemplateVariables) {
Matcher matcher = this.pattern.matcher(str);
if (matcher.matches()) {
if (uriTemplateVariables != null) {
// 這里會循環(huán)獲取@RequestMapping中配置的參數(shù)名,并從url中獲取對應(yīng)的值稚疹,然后put進(jìn)map中
for (int i = 1; i <= matcher.groupCount(); i++) {
String name = this.variableNames.get(i - 1);
String value = matcher.group(i);
uriTemplateVariables.put(name, value);
}
}
return true;
} else {
return false;
}
}
由于有朋友反饋流程圖形式可能比代碼形式更有利于閱讀和理解居灯,因此本文將首次嘗試以時序圖的形式來分析以簡短篇幅。希望大家有什么意見或建議可以積極的和我反饋。我也會積極修改展現(xiàn)方式以達(dá)到更好的傳播方式怪嫌。
SpringMVC執(zhí)行過程.png
至此SpringMVC的簡單流程也就結(jié)束了义锥,其他相對復(fù)雜的數(shù)據(jù)結(jié)構(gòu)(例如JSON、數(shù)組及文件上傳等)暫時沒有分析岩灭。但是具體過程大同小異拌倍,后面有機(jī)會的話我們在逐一分析。另外考慮到現(xiàn)在越來越多的公司使用前后端分離川背,因此對于視圖解析這部分也沒有做詳細(xì)分析贰拿,希望大家見諒蛤袒。