AbstractUrlHandlerMapping 是 SpringMVC 中基於 URL 映射的 HandlerMapping 基類,核心職責:根據請求路徑找到對應的 Handler,並封裝成 HandlerExecutionChain(包含攔截器鏈)。
模板方法,子類實作具體查找邏輯(如 SimpleUrlHandlerMapping 從 Map 查找,RequestMappingHandlerMapping 掃描 @RequestMapping)。
入口方法,流程:
getHandlerInternal 取得原始 Handler。validateHandler,預設空實現,子類可擴展)。HandlerExecutionChain:buildPathExposingHandler。封裝 Handler 並添加兩個內建攔截器:
PathExposingHandlerInterceptor:暴露 bestMatchingPattern、pathWithinMapping 到請求屬性,供後續處理器使用。UriTemplateVariablesHandlerInterceptor:暴露 URI 模板變數(如 /user/{id} 中的 id)。protected Object buildPathExposingHandler(Object rawHandler, String bestMatchingPattern,
String pathWithinMapping, Map uriTemplateVariables) {
HandlerExecutionChain chain = new HandlerExecutionChain(rawHandler);
chain.addInterceptor(new PathExposingHandlerInterceptor(bestMatchingPattern, pathWithinMapping));
if (!CollectionUtils.isEmpty(uriTemplateVariables)) {
chain.addInterceptor(new UriTemplateVariablesHandlerInterceptor(uriTemplateVariables));
}
return chain;
}
getHandler 模板、攔截器管理、CORS 支援。UrlPathHelper、PathMatcher)。@RequestMapping、@GetMapping 等註解。public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping {
// ...
@Override
protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
Object handler = lookupHandler(lookupPath, request);
return handler;
}
protected abstract Object lookupHandler(String lookupPath, HttpServletRequest request);
protected void validateHandler(Object handler, HttpServletRequest request) throws Exception { }
// buildPathExposingHandler 見上文
}
AbstractUrlHandlerMapping 並實作 lookupHandler。buildPathExposingHandler,可覆寫調整暴露屬性邏輯。bestMatchingPattern 與 pathWithinMapping 的區別,有助於編寫通用攔截器。