Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

搞懂 Spring MVC 的 HandlerMapping 與 HandlerAdapter 如何協作

從一個同事的提問說起

「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)), "/*");
  • ContextLoaderListener:Web 容器啟動時載入 ApplicationContext,建立 ROOT 上下文,可接收 XML 型別的實作(如 XmlWebApplicationContext)。這裡不是重點。
  • DispatcherServlet:前端控制器,Spring MVC 的統一入口,負責分派與調度。它的初始化階段會建立各類策略物件,其中就包含 HandlerMapping 與 HandlerAdapter。
@Override
protected void onRefresh(ApplicationContext context) {
    initStrategies(context);
}

protected void initStrategies(ApplicationContext context) {
    // 其它初始化
    initHandlerMappings(context);
    initHandlerAdapters(context);
    // 其它初始化
}

HandlerMapping:回答「誰來處理」

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);
        }
    }
    // 不加載全部的邏輯與默認邏輯在此省略
}

HandlerAdapter:回答「怎麼呼叫」

找到 handler 之後還不能直接呼叫,Spring 需要一個适配器把各種形態的 handler 統一成一個介面。HandlerAdapter 的 handle 方法負責真正呼叫 handler 並返回 ModelAndView,其中的 argumentResolvers 處理方法參數,messageConverters 負責訊息轉換。

doDispatch:三步走完一次請求

  • 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,最後由它執行。兩者一前一後,缺一不可。

Copyright © Linux教程網 All Rights Reserved