SpringMVC請求與Controller如何匹配【簡易版】
當spring 接到請求後,DispatcherServlet如何找到對應的Controller
1、spring初始化時期
1)會對所有的bean進行載入(此處只討論註解定義bean),判斷bean中是否帶有@Controller 註解或者 @RequestMapping 註解,若有則該bean為一個Handler。
問:如果僅有@RequestMapping 註解,是否會為Handler?
答:不會。因為僅有@RequestMapping註解,spring初始化時,不會將該類作為bean。
問:如果將一個@Service的bean,加上 @RequestMapping 註解,是否會為Handler?
答:會。但是一般用@Controller。
2)獲取Handler例項中含有 @RequestMapping 的方法,該方法為一個HandlerMethod,@RequestMapping 中的屬性值封裝到RequestMappingInfo中。
即每一個RequestMappingInfo 對應一個 HandlerMethod ,將其存放在map<RequestMappingInfo, HandlerMethod>
3)將Handler中@RequestMapping 中value 和 HandlerMethod 中的value 合併成 url。
將HandlerMethod 的url 和 RequestMappingInfo 存放在urlMap<url, RequestMappingInfo> 中。
2、發起請求
1)在urlMap 中查詢對應的url,獲取RequestMappingInfo。
2)在map中查詢對應RequestMappingInfo,獲取對應的HandlerMethod。該方法則是請求所對應的處理方法。