SpringMVC源碼分析(7)剖析HandlerAdapter

SpringMVC中,和HandlerMapping同樣重要的一個組件,就是HandlerAdapter。java

若是說HandlerMapping是溝通請求和後端Controller的橋樑。HandlerAdapter則是負責具體處理請求核心工做了,另一個處理請求的責任系列攔截器,前面已經說過了。後端

HandlerMapping和HandlerAdapter,看名字怎麼都像弟兄倆。確實二者關係不通常,全部解析出的HandlerMapping,都通通適配一個合適的HandlerAdapter來負責具體處理事務。app

wKiom1hD9wnQL7S2AAAY6K0VLVQ981.png


做用

SimpleServletHandlerAdapter
ide

處理Servlet 接口ui

默認不激活
this

SimpleControllerHandlerAdapter
處理 Controller接口
HttpRequestHandlerAdapter  處理HttpRequestHandler 接口
AnnotationMethodHandlerAdapter
處理 handler methods


1.HandlerAdapter 初始時機
spa


wKioL1hD-_GhqILoAADDvcLTTis254.png

1.AnnotationDrivenBeanDefinitionParser.parse(),註冊了AnnotationMethodHandlerAdapter;blog

2.AbstractHttpRequestHandlerBeanDefinitionParser.registerHandlerAdapterIfNecessary()註冊了HttpRequestHandlerAdapter;
3.ViewControllerBeanDefinitionParser.registerHanderAdapter註冊了接口

SimpleControllerHandlerAdapter;事務

4.ComplexWebApplicationContext.refresh()註冊了SimpleServletHandlerAdapter,默認不激活。

總結:HandlerAdapter是在解析標籤時已經初始化完畢了。

介紹完了Adapter是如何初始化,初始化到容器中。接下來能夠討論內部實現原理了。

2.HandlerAdapter 工做原理

2.1 接口

wKioL1hD_jyiBwaQAAAQyEvc9co002.png

public interface HandlerAdapter {
   
   /**
    * 判斷是否支持Handler
    */
   boolean supports(Object handler); 
   
   /**
    * Use the given handler to handle this request.
    * The workflow that is required may vary widely.
    * 使用Handler處理請求
    */
   ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;

   /**
    * Same contract as for HttpServlet'
    */
   long getLastModified(HttpServletRequest request, Object handler);

}

2.2 AnnotationMethodHandlerAdapter介紹

AnnotationMethodHandlerAdapter是幾個爲數很少Handler中最重要的一個處理類。

經過它,能夠將請求適配到匹配的某個Handler的具體方法上。

wKiom1hD_mKzs51gAAA3smKYOlE443.png

2.3 AnnotationMethodHandlerAdapter處理序列圖

wKioL1hECVXTAUEtAADpKzdaGmQ005.png

圖畫的感受挺多,但總結起來,就作了兩件事。

  1. 匹配尋找合適的方法

  2. 調用方法,構造mav視圖

wKiom1hEDHnxkNsUAABNPRzvNvA416.png

相關文章
相關標籤/搜索