Skip to content

Instantly share code, notes, and snippets.

@biaocy
Created March 27, 2018 03:25
Show Gist options
  • Save biaocy/f24ccf202d8e05db86d56053c32f13ff to your computer and use it in GitHub Desktop.
Save biaocy/f24ccf202d8e05db86d56053c32f13ff to your computer and use it in GitHub Desktop.
how spring mvc work
Blog about "How Spring Mvc Work"
1.how request url match? Hint: With namespace <mvc:annotation-driven />, it's use of RequestMappingHandleMapping.
A.With "WebMVC" enabled, it will register a couple of HandleMapping and HandleAdapter
当 "WebMVC" enabled 时,Spring 默认会注册一些 HandleMapping 和 HandleAdapter
By default:
1.RequestMappingHandleMapping
2.RequestMappingHandlerAdapter
B.When "RequestMappingHandleMapping" instantiation
当 "RequestMappingHandleMapping" 初始化时,通过回调 afterPropertiesSet(Initialization callback) 方法检测 HandlerMethod:
1.筛选出符合条件的 Handler( @Controller or @RequestMapping )
2.通过 MethodIntrospector.selectMethods 方法生成对应 Handler 的 RequestMappingInfo
3.根据生成的 RequestMappingInfo,注册对应 HandlerMethod(//@TODO MappingRegistry相关介绍),供 request 匹配 Handler 使用
C.Spring MVC 是如何处理请求的
1.首先 DispatcherServlet#doService 加载框架相关的请求属性,如:WebApplicationContext, LocaleResolver, ThemeResolver, ThemeSource等
2.1.其次 DispatcherServlet#doDispatch 根据请求匹配 Handler;
2.2.再根据 Handler 匹配 HandlerAdapter;
2.3. // Last-Modifed
2.3.调用已经注册的 interceptors#preHandle 方法,若无需继续处理则返回。
2.4.通过 HandlerAdapter 继续处理请求;
2.5.RequestMappingHandlerAdapter#invokeHandlerMethod,设置 ArgumentResolver、ReturnValueHandler 等供解析参数、处理 Handler 返回值等
2.6.ServletInvocableHandlerMethod#invokeAndHandle,解析 Handler 参数、处理 Handler 返回值
2.7.RequestMappingHandlerAdapter#invokeHandlerMethod, 构造ModelAndView返回
2.8.调用已经注册的 interceptors#postHandle 方法
3.DispatcherServlet#processingDispatchResult 处理上面返回的 ModelAndView;
3.1.若无异常则继续,若有异常则处理渲染异常 view
3.2.若未渲染 view,则交及 ViewResolver 解析 view 并渲染。至此,请求处理结束。
D. 记录 ViewResolver、HandlerMapping、HandlerAdatper、LocaleResolver、ArgumentResolver、ReturnValueHandler、Interceptor 等 Component 的注册 (hint: 1.默认策略;2. mvc namespace/@EnableMvc策略)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment