笔记来源:【尚硅谷】SpringMVC教程丨一套快速上手spring mvc

SpringMVC 执行流程

1、SpringMVC 常用组件

  • DispatcherServlet:前端控制器,不需要工程师开发,由框架提供

    • 作用:统一处理请求和响应,整个流程控制的中心,由它调用其它组件处理用户的请求
  • HandlerMapping:处理器映射器,不需要工程师开发,由框架提供

    • 作用:根据请求的 url、method 等信息查找Handler,即控制器方法
  • Handler:处理器,需要工程师开发

    • 作用:在DispatcherServlet的控制下Handler对具体的用户请求进行处理
  • HandlerAdapter:处理器适配器,不需要工程师开发,由框架提供

    • 作用:通过HandlerAdapter对处理器(控制器方法)进行执行
  • ViewResolver:视图解析器,不需要工程师开发,由框架提供

    • 作用:进行视图解析,得到相应的视图,例如:ThymeleafViewInternalResourceViewRedirectView
  • View:视图

    • 作用:将模型数据通过页面展示给用户

2、DispatcherServlet 初始化过程

DispatcherServlet本质上是一个 Servlet,所以天然的遵循 Servlet 的生命周期,宏观上是 Servlet 生命周期来进行调度

09-SpringMVC 执行流程 - 图1

09-SpringMVC 执行流程 - 图2

2.1、初始化 WebApplicationContext

所在类:org.springframework.web.servlet.FrameworkServlet

  1. protected WebApplicationContext initWebApplicationContext() {
  2. WebApplicationContext rootContext =
  3. WebApplicationContextUtils.getWebApplicationContext(getServletContext());
  4. WebApplicationContext wac = null;
  5. if (this.webApplicationContext != null) {
  6. wac = this.webApplicationContext;
  7. if (wac instanceof ConfigurableWebApplicationContext) {
  8. ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
  9. if (!cwac.isActive()) {
  10. if (cwac.getParent() == null) {
  11. cwac.setParent(rootContext);
  12. }
  13. configureAndRefreshWebApplicationContext(cwac);
  14. }
  15. }
  16. }
  17. if (wac == null) {
  18. wac = findWebApplicationContext();
  19. }
  20. if (wac == null) {
  21. // 创建ApplicationContext
  22. wac = createWebApplicationContext(rootContext);
  23. }
  24. if (!this.refreshEventReceived) {
  25. synchronized (this.onRefreshMonitor) {
  26. // 刷新ApplicationContext
  27. onRefresh(wac);
  28. }
  29. }
  30. if (this.publishContext) {
  31. String attrName = getServletContextAttributeName();
  32. // 将IOC容器在应用域共享
  33. getServletContext().setAttribute(attrName, wac);
  34. }
  35. return wac;
  36. }

2.2、创建 WebApplicationContext

所在类:org.springframework.web.servlet.FrameworkServlet

  1. protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent) {
  2. Class<?> contextClass = getContextClass();
  3. if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
  4. throw new ApplicationContextException(
  5. "Fatal initialization error in servlet with name '" + getServletName() +
  6. "': custom WebApplicationContext class [" + contextClass.getName() +
  7. "] is not of type ConfigurableWebApplicationContext");
  8. }
  9. // 反射创建IOC容器对象
  10. ConfigurableWebApplicationContext wac =
  11. (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
  12. wac.setEnvironment(getEnvironment());
  13. // 设置父容器:将Spring上下文对象作为SpringMVC上下文对象的父容器
  14. wac.setParent(parent);
  15. String configLocation = getContextConfigLocation();
  16. if (configLocation != null) {
  17. wac.setConfigLocation(configLocation);
  18. }
  19. configureAndRefreshWebApplicationContext(wac);
  20. return wac;
  21. }

2.3、DispatcherServlet 初始化策略

FrameworkServlet创建WebApplicationContext后,调用onRefresh(wac)刷新容器

此方法在DispatcherServlet中进行了重写,调用了initStrategies(context)方法,初始化策略,即初始化DispatcherServlet的各个组件

所在类:org.springframework.web.servlet.DispatcherServlet

  1. protected void initStrategies(ApplicationContext context) {
  2. // 初始化文件上传解析器
  3. initMultipartResolver(context);
  4. initLocaleResolver(context);
  5. initThemeResolver(context);
  6. // 初始化处理器映射
  7. initHandlerMappings(context);
  8. // 初始化处理器适配器
  9. initHandlerAdapters(context);
  10. // 初始化处理器异常处理器
  11. initHandlerExceptionResolvers(context);
  12. initRequestToViewNameTranslator(context);
  13. // 初始化视图解析器
  14. initViewResolvers(context);
  15. initFlashMapManager(context);
  16. }

3、DispatcherServlet 调用组件处理请求

3.1、processRequest

FrameworkServlet重写HttpServlet中的service()doXxx(),这些方法中调用了processRequest(request,response)

所在类:org.springframework.web.servlet.FrameworkServlet

  1. protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
  2. throws ServletException, IOException {
  3. long startTime = System.currentTimeMillis();
  4. Throwable failureCause = null;
  5. LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
  6. LocaleContext localeContext = buildLocaleContext(request);
  7. RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
  8. ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
  9. WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
  10. asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());
  11. initContextHolders(request, localeContext, requestAttributes);
  12. try {
  13. // 重点关注
  14. doService(request, response);
  15. }
  16. catch (ServletException | IOException ex) {
  17. failureCause = ex;
  18. throw ex;
  19. }
  20. catch (Throwable ex) {
  21. failureCause = ex;
  22. throw new NestedServletException("Request processing failed", ex);
  23. }
  24. finally {
  25. resetContextHolders(request, previousLocaleContext, previousAttributes);
  26. if (requestAttributes != null) {
  27. requestAttributes.requestCompleted();
  28. }
  29. logResult(request, response, failureCause, asyncManager);
  30. publishRequestHandledEvent(request, response, startTime, failureCause);
  31. }
  32. }

3.2、doService

所在类:org.springframework.web.servlet.DispatcherServlet

  1. protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
  2. logRequest(request);
  3. Map<String, Object> attributesSnapshot = null;
  4. if (WebUtils.isIncludeRequest(request)) {
  5. attributesSnapshot = new HashMap<>();
  6. Enumeration<?> attrNames = request.getAttributeNames();
  7. while (attrNames.hasMoreElements()) {
  8. String attrName = (String) attrNames.nextElement();
  9. if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) {
  10. attributesSnapshot.put(attrName, request.getAttribute(attrName));
  11. }
  12. }
  13. }
  14. request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
  15. request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
  16. request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);
  17. request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());
  18. if (this.flashMapManager != null) {
  19. FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);
  20. if (inputFlashMap != null) {
  21. request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));
  22. }
  23. request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
  24. request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);
  25. }
  26. RequestPath previousRequestPath = null;
  27. if (this.parseRequestPath) {
  28. previousRequestPath = (RequestPath) request.getAttribute(ServletRequestPathUtils.PATH_ATTRIBUTE);
  29. ServletRequestPathUtils.parseAndCache(request);
  30. }
  31. try {
  32. // 重点关注
  33. doDispatch(request, response);
  34. }
  35. finally {
  36. if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
  37. if (attributesSnapshot != null) {
  38. restoreAttributesAfterInclude(request, attributesSnapshot);
  39. }
  40. }
  41. if (this.parseRequestPath) {
  42. ServletRequestPathUtils.setParsedRequestPath(previousRequestPath, request);
  43. }
  44. }
  45. }

3.3、doDispatch

所在类:org.springframework.web.servlet.DispatcherServlet

  1. protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
  2. HttpServletRequest processedRequest = request;
  3. HandlerExecutionChain mappedHandler = null;
  4. boolean multipartRequestParsed = false;
  5. WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
  6. try {
  7. ModelAndView mv = null;
  8. Exception dispatchException = null;
  9. try {
  10. processedRequest = checkMultipart(request);
  11. multipartRequestParsed = (processedRequest != request);
  12. // 包含handler、interceptorList、interceptorIndex
  13. // handler:浏览器发送的请求所匹配的控制器方法
  14. // interceptorList:处理控制器方法的所有拦截器集合
  15. // interceptorIndex:拦截器索引,控制拦截器aftercompletion()的执行
  16. mappedHandler = getHandler(processedRequest);
  17. if (mappedHandler == null) {
  18. noHandlerFound(processedRequest, response);
  19. return;
  20. }
  21. // 创建处理器适配器,负责调用控制器方法
  22. HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
  23. String method = request.getMethod();
  24. boolean isGet = HttpMethod.GET.matches(method);
  25. if (isGet || HttpMethod.HEAD.matches(method)) {
  26. long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
  27. if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
  28. return;
  29. }
  30. }
  31. // 调用拦截器preHandle方法,正序执行
  32. if (!mappedHandler.applyPreHandle(processedRequest, response)) {
  33. return;
  34. }
  35. // 由处理器适配器调用具体的控制器方法,最终获得ModelAndview对象
  36. mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
  37. if (asyncManager.isConcurrentHandlingStarted()) {
  38. return;
  39. }
  40. applyDefaultViewName(processedRequest, mv);
  41. // 调用拦截器postHandle方法,反序执行
  42. mappedHandler.applyPostHandle(processedRequest, response, mv);
  43. }
  44. catch (Exception ex) {
  45. dispatchException = ex;
  46. }
  47. catch (Throwable err) {
  48. dispatchException = new NestedServletException("Handler dispatch failed", err);
  49. }
  50. // 后续处理:处理模型数据和渲染视图
  51. processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
  52. }
  53. catch (Exception ex) {
  54. triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
  55. }
  56. catch (Throwable err) {
  57. triggerAfterCompletion(processedRequest, response, mappedHandler,
  58. new NestedServletException("Handler processing failed", err));
  59. }
  60. finally {
  61. if (asyncManager.isConcurrentHandlingStarted()) {
  62. if (mappedHandler != null) {
  63. mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
  64. }
  65. }
  66. else {
  67. if (multipartRequestParsed) {
  68. cleanupMultipart(processedRequest);
  69. }
  70. }
  71. }
  72. }

3.4、processDispatchResult

所在类:org.springframework.web.servlet.DispatcherServlet

  1. private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,
  2. @Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv,
  3. @Nullable Exception exception) throws Exception {
  4. boolean errorView = false;
  5. if (exception != null) {
  6. if (exception instanceof ModelAndViewDefiningException) {
  7. logger.debug("ModelAndViewDefiningException encountered", exception);
  8. mv = ((ModelAndViewDefiningException) exception).getModelAndView();
  9. }
  10. else {
  11. Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
  12. mv = processHandlerException(request, response, handler, exception);
  13. errorView = (mv != null);
  14. }
  15. }
  16. if (mv != null && !mv.wasCleared()) {
  17. // 处理模型数据和渲染视图
  18. render(mv, request, response);
  19. if (errorView) {
  20. WebUtils.clearErrorRequestAttributes(request);
  21. }
  22. }
  23. else {
  24. if (logger.isTraceEnabled()) {
  25. logger.trace("No view rendering, null ModelAndView returned.");
  26. }
  27. }
  28. if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
  29. return;
  30. }
  31. if (mappedHandler != null) {
  32. // 调用拦截器afterCompletion方法,反序执行
  33. mappedHandler.triggerAfterCompletion(request, response, null);
  34. }
  35. }

4、SpringMVC 执行流程

1)用户向服务器发送请求,请求被 SpringMVC 前端控制器DispatcherServlet捕获

2)DispatcherServlet对请求 URL 进行解析,得到请求资源标识符 URI ,判断请求 URI 对应的映射是否存在:

若不存在,再判断是否配置了mvc:default-servlet-handler

  • i.如果没配置,则控制台报映射查找不到,客户端展示 404 错误
  1. DEBUG org.springframework.web.servlet.Dispatcherservlet - GET "/springMVC/testHaha", parameters={}
  2. WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /springMVC/testHaha
  3. DEBUG org.springframework.web.servlet.Dispatcherservlet - Completed 404 NOT_FOUND
  • ii.如果有配置,则访问目标资源(一般为静态资源,如:JS,CSS,HTML),找不到客户端也会展示404错误
    1. DEBUG org.springframework.web.servlet.Dispatcherservlet - GET "/springMVC/testHaha", parameters={}
    2. handler.SimpleUrlHandlerMapping Mapped to org.springframework.web.servlet.resource.DefaultServletHttpRequestHandlerDispatcherservlet - Completed 404 NOT_FOUND

若存在,则执行一下流程

3)根据该 URI,调用HandlerMapping获得该Handler配置的所有相关的对象(包括Handler对象以及Handler对象对应的拦截器),最后以HandlerExecutionChain执行链对象的形式返回

4)DispatcherServlet根据获得的Handler,选择一个合适的HandlerAdapter

5)如果成功获得HandlerAdapter,此时将开始执行拦截器的preHandler()方法【正向】

6)提取 Request 中的模型数据,填充Handler入参,开始执行Handler(Controller)方法,处理请求。在填充Handler的入参过程中,根据你的配置,Spring 将帮你做一些额外的工作:

  • a)HttpMessageConveter:将请求消息(如 json、xml 等数据)转换成一个对象,将对象转换为指定的响应信息
  • b)数据转换:对请求消息进行数据转换。如 String 转换成 Integer、Double 等
  • c)数据格式化:对请求消息进行数据格式化。如将字符串转换成格式化数字或格式化日期等
  • d)数据验证:验证数据的有效性(长度、格式等),验证结果存储到 BindingResult 或 Error 中

7)Handler执行完成后,向DispatcherServlet返回一个ModelAndView对象

8)此时将开始执行拦截器的postHandle()方法【逆向】

9)根据返回的ModelAndView(此时会判断是否存在异常,如果存在异常,则执行HandlerExceptionResolver进行异常处理)选择一个适合的ViewResolver进行视图解析,根据ModelView,来渲染视图

10)渲染视图完毕执行拦截器的afterCompletion()方法【逆向】

11)将渲染结果返回给客户端

总结

本届重点掌握

  • SpringMVC 常用组件
  • DispatcherServlet 的初始化过程和调用方法
  • SpringMVC 执行流程

附上导图,仅供参考

09-SpringMVC 执行流程 - 图3