「HandlerMapping 和 HandlerAdapter 到底有什麼關係?」——用 Spring MVC 有一段時間了,但脫口而出的只有兩個關鍵詞:
@RequestMapping:每個 action 上標一個路徑,請求進來後靠它找到該由哪個 Controller 的哪個方法處理,本質是 URL 到程式碼的路由。@RequestMapping(value = "/bss/{priceId}", method = RequestMethod.GET)
public ValueResult<ProductPrice> getProductPrice(HttpServletRequest request,
@Min(value = 1, message = "priceId不合法") @PathVariable final long priceId) {
// 省略
}
HandlerInterceptor:做請求攔截、權限校驗時常用。兩者都沾一點邊,但都不是答案核心。真正的問題是:這兩個介面各自負責什麼,彼此怎麼互動。最快的辦法就是跟著一個請求走一遍。
典型的 Spring MVC 應用會有兩份配置:應用級的 applicationContext.xml(資料庫、Redis 等非 Web 配置)與 Web 級的 mvc-dispatcher-servlet.xml(專注 MVC)。
XmlWebApplicationContext context = new XmlWebApplicationContext();
context.setConfigLocations(new String[]{"classpath*:applicationContext.xml","classpath*:spring/mvc-dispatcher-servlet.xml"});
ServletContextHandler spingMvcHandler = new ServletContextHandler();
spingMvcHandler.setContextPath(appConfig.getContext());
spingMvcHandler.addEventListener(new ContextLoaderListener(context));
spingMvcHandler.addServlet(new ServletHolder(new DispatcherServlet(context)), "/*");
XmlWebApplicationContext)。這裡不是重點。@Override
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
}
protected void initStrategies(ApplicationContext context) {
// 其它初始化
initHandlerMappings(context);
initHandlerAdapters(context);
// 其它初始化
}
initHandlerMappings 透過 BeanFactoryUtils.beansOfTypeIncludingAncestors 收集容器中的 HandlerMapping。其中最重要的是 RequestMappingHandlerMapping,我們在方法上寫的 @RequestMapping 資訊會被註冊到它的 mappingRegistry 中,那裡保存著全部請求路由。
private void initHandlerMappings(ApplicationContext context) {
this.handlerMappings = null;
if (this.detectAllHandlerMappings) {
// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
Map<String, HandlerMapping> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());
// We keep HandlerMappings in sorted order.
AnnotationAwareOrderComparator.sort(this.handlerMappings);
}
}
// 不加載全部的邏輯與默認邏輯在此省略
}
找到 handler 之後還不能直接呼叫,Spring 需要一個适配器把各種形態的 handler 統一成一個介面。HandlerAdapter 的 handle 方法負責真正呼叫 handler 並返回 ModelAndView,其中的 argumentResolvers 處理方法參數,messageConverters 負責訊息轉換。
getHandler:取得頁面處理器,也就是決定由哪個 Controller 的哪個方法執行,含方法與參數資訊。getHandlerAdapter:依 handler 取得對應的 HandlerAdapter。HandlerAdapter.handle:執行真實處理。protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 初始化省略
try {
ModelAndView mv = null;
Exception dispatchException = null;
try {
processedRequest = checkMultipart(request);
multipartRequestParsed = (processedRequest != request);
// Determine handler for the current request.
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(processedRequest, response);
return;
}
// Determine handler adapter for the current request.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
// 其它邏輯省略
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
// 其它邏輯省略
} catch (Exception ex) {
dispatchException = ex;
}
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
// 異常邏輯省略
}
HandlerMapping 負責「找得到」——把請求映射到具體的 handler;HandlerAdapter 負責「調得動」——按統一介面去呼叫各種形態的 handler,並在這過程中完成參數解析與訊息轉換。doDispatch 先問 HandlerMapping 要 handler,再依 handler 換到對應的 HandlerAdapter,最後由它執行。兩者一前一後,缺一不可。