1耍休, 初始化
1.1 web.xml
基于web.xml跷叉,通過ContextLoaderListener在servlet容器啟動(dòng)時(shí)初始化WebApplicationContext顿锰,然后放入ServletContext的WebApplicationContext.class.getName() + ".ROOT"屬性中。
1.2距芬, 基于注解
servlet 3.1 規(guī)范 8.2.4節(jié)
The ServletContainerInitializer class is looked up via the jar services API. For each application, an instance of the ServletContainerInitializer is created by the container at application startup time. The framework providing an implementation of the ServletContainerInitializer MUST bundle in the META-INF/services directory of the jar file a file called javax.servlet.ServletContainerInitializer, as per the jar services API, that points to the implementation class of the ServletContainerInitializer.
In addition to the ServletContainerInitializer we also have an annotation - HandlesTypes. The HandlesTypes annotation on the implementation of the ServletContainerInitializer is used to express interest in classes that may have annotations (type, method or field level annotations) specified in the value of the HandlesTypes or if it extends / implements one those classes anywhere in the class’ super types. The HandlesTypes annotation is applied irrespective of the setting of metadata-complete.
servlet容器在加載web應(yīng)用時(shí)悔常,會(huì)查找META-INF/services文件夾下文件名為javax.servlet.ServletContainerInitializer的文件的內(nèi)容,文件內(nèi)容為ServletContainerInitializer的實(shí)現(xiàn)類想括。HandlesTypes注解指定的類型的所有類會(huì)傳遞給ServletContainerInitializer#onStartup
2 陷谱, ContextLoaderListener
3, DispatcherServlet
3.1 初始化
根據(jù)配置瑟蜈,初始化各個(gè)策略接口烟逊。
3.2 doService
把FlashMap,WebApplicationContext等放入request
doDispatch處理流程
3.2.1 檢查是否文件上傳
3.2.2 根據(jù)handlerMappings和請(qǐng)求獲取HandlerExecutionChain
從DispatcherServlet.properties可以看出HandlerMapping實(shí)現(xiàn)類為BeanNameUrlHandlerMapping和RequestMappingHandlerMapping
AbstractHandlerMapping
抽象模版設(shè)計(jì)模式:根據(jù)請(qǐng)求獲取handler铺根,加入攔截器鏈宪躯。
BeanNameUrlHandlerMapping的實(shí)現(xiàn)機(jī)制是根據(jù)/開頭的bean別名匹配請(qǐng)求
RequestMappingHandlerMapping的實(shí)現(xiàn)機(jī)制是檢查BeanFactory中所有bean中RequestMapping注解的方法,加入MappingRegistry注冊(cè)表
![createRequestMappingInfo.io/upload_images/11548923-fb373da124807a4f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
查找MappingRegistry注冊(cè)表
3.2.3 獲取handler之后位迂,查找與之匹配的HandlerAdapter访雪,由HandlerAdapter來處理各種handler,統(tǒng)一返回ModelAndView掂林。
DispatcherServlet.properties中HandlerAdapter的子類為HttpRequestHandlerAdapter臣缀,SimpleControllerHandlerAdapter,RequestMappingHandlerAdapter
HttpRequestHandlerAdapter處理HttpRequestHandler泻帮,不返回ModelAndView精置,自己返回響應(yīng)信息
SimpleControllerHandlerAdapter處理實(shí)現(xiàn)Controller接口的handler
RequestMappingHandlerAdapter處理HandlerMethod,根據(jù)注冊(cè)的HandlerMethodReturnValueHandler處理handler返回值锣杂。
handler返回異步結(jié)果時(shí)才會(huì)異步處理V搿7!
spring-mvc請(qǐng)求處理流程赖阻,很多細(xì)節(jié)還需要完善5骸!火欧!