springmvc源码分析

简介: springmvc源码分析


image.png

1.springmvc流程分析

各种书上通用写的springmvc流程是这样的:

  1. 用户发送请求至前端控制器DispatcherServlet。
  2. DispatcherServlet收到请求调用HandlerMapping处理器映射器。
  3. 处理器映射器找到具体的处理器(可以根据xml配置、注解进行查找),生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。(也就是HandlerExecutionChain)
  4. DispatcherServlet调用HandlerAdapter处理器适配器。
  5. HandlerAdapter经过适配调用具体的处理器(Controller,也叫后端控制器)。
  6. Controller执行完成返回ModelAndView。
  7. HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet。
  8. DispatcherServlet将ModelAndView传给ViewReslover视图解析器。
  9. ViewReslover解析后返回具体View.
  10. DispatcherServlet根据View进行渲染视图(即将模型数据填充至视图中)。
  11. DispatcherServlet响应用户。

image.png

2.源码分析

1.发送服务,调用servlet

servlet通过doGet和doPost执行方法 ,这两个方法在DispatcherServlet的父类FrameworkServlet中,其中调用到了doService。

1. protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
2. this.processRequest(request, response);
3.     }
1. protected final void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
2. long startTime = System.currentTimeMillis();
3. Throwable failureCause = null;
4. LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
5. LocaleContext localeContext = this.buildLocaleContext(request);
6. RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
7. ServletRequestAttributes requestAttributes = this.buildRequestAttributes(request, response, previousAttributes);
8. WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
9.         asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new FrameworkServlet.RequestBindingInterceptor());
10. this.initContextHolders(request, localeContext, requestAttributes);
11. 
12. try {
13. this.doService(request, response);
14.         } catch (IOException | ServletException var16) {
15.             failureCause = var16;
16. throw var16;
17.         } catch (Throwable var17) {
18.             failureCause = var17;
19. throw new NestedServletException("Request processing failed", var17);
20.         } finally {
21. this.resetContextHolders(request, previousLocaleContext, previousAttributes);
22. if (requestAttributes != null) {
23.                 requestAttributes.requestCompleted();
24.             }
25. 
26. this.logResult(request, response, (Throwable)failureCause, asyncManager);
27. this.publishRequestHandledEvent(request, response, startTime, (Throwable)failureCause);
28.         }
29. 
30.     }
1. protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
2. 
3. this.logRequest(request);
4.         Map<String, Object> attributesSnapshot = null;
5. if (WebUtils.isIncludeRequest(request)) {
6.             attributesSnapshot = new HashMap();
7.             Enumeration attrNames = request.getAttributeNames();
8. 
9.             label95:
10. while(true) {
11.                 String attrName;
12. do {
13. if (!attrNames.hasMoreElements()) {
14. break label95;
15.                     }
16. 
17.                     attrName = (String)attrNames.nextElement();
18.                 } while(!this.cleanupAfterInclude && !attrName.startsWith("org.springframework.web.servlet"));
19. 
20.                 attributesSnapshot.put(attrName, request.getAttribute(attrName));
21.             }
22.         }
23. //设置属性
24. //ApplicationContext、localeResolver、themeResolver等对象添加到request中
25.         request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.getWebApplicationContext());
26.         request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
27.         request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);
28.         request.setAttribute(THEME_SOURCE_ATTRIBUTE, this.getThemeSource());
29. if (this.flashMapManager != null) {
30.             FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);
31. if (inputFlashMap != null) {
32.                 request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));
33.             }
34. 
35.             request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
36.             request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);
37.         }
38. 
39. try {
40. //具体的方法
41. this.doDispatch(request, response);
42.         } finally {
43. if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted() && attributesSnapshot != null) {
44. this.restoreAttributesAfterInclude(request, attributesSnapshot);
45.             }
46. 
47.         }
48. 
49.     }

2.doDispatch

大部分操作都是在这个类中。

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. 
7. try {
8. try {
9. ModelAndView mv = null;
10. Object dispatchException = null;
11. 
12. try {
13. // 1. 检查是否是上传文件
14.                     processedRequest = this.checkMultipart(request);
15.                     multipartRequestParsed = processedRequest != request;
16. 
17. //获取到controller在factory中的所有bean的信息
18.                     mappedHandler = this.getHandler(processedRequest);
19. 
20. if (mappedHandler == null) {
21. this.noHandlerFound(processedRequest, response);
22. return;
23.                     }
24. 
25. //获取到处理器 也就是controller类 
26. HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.getHandler());
27. 
28. String method = request.getMethod();
29. boolean isGet = "GET".equals(method);
30. if (isGet || "HEAD".equals(method)) {
31. // 如果是get 根据上次修改的时间戳来判断资源是否已被修改,如果资源未被修改,则直接返回,浏览器将使用缓存
32. long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
33. if ((new ServletWebRequest(request, response)).checkNotModified(lastModified) && isGet) {
34. return;
35.                         }
36.                     }
37. 
38. if (!mappedHandler.applyPreHandle(processedRequest, response)) {
39. return;
40.                     }
41. 
42.                     mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
43. if (asyncManager.isConcurrentHandlingStarted()) {
44. return;
45.                     }
46. 
47. this.applyDefaultViewName(processedRequest, mv);
48. //后置处理器
49.                     mappedHandler.applyPostHandle(processedRequest, response, mv);
50.                 } catch (Exception var20) {
51.                     dispatchException = var20;
52.                 } catch (Throwable var21) {
53.                     dispatchException = new NestedServletException("Handler dispatch failed", var21);
54.                 }
55. 
56. this.processDispatchResult(processedRequest, response, mappedHandler, mv, (Exception)dispatchException);
57.             } catch (Exception var22) {
58. this.triggerAfterCompletion(processedRequest, response, mappedHandler, var22);
59.             } catch (Throwable var23) {
60. this.triggerAfterCompletion(processedRequest, response, mappedHandler, new NestedServletException("Handler processing failed", var23));
61.             }
62. 
63.         } finally {
64. if (asyncManager.isConcurrentHandlingStarted()) {
65. if (mappedHandler != null) {
66.                     mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
67.                 }
68.             } else if (multipartRequestParsed) {
69. this.cleanupMultipart(processedRequest);
70.             }
71. 
72.         }
73.     }

1.getHandler方法

获取处理器映射器

1. @Nullable
2. protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
3. 
4. //mapping中放着所有的mapping信息
5. if (this.handlerMappings != null) {
6. Iterator var2 = this.handlerMappings.iterator();
7. 
8. while(var2.hasNext()) {
9. HandlerMapping mapping = (HandlerMapping)var2.next();
10. 
11. //关键方法 获取bean信息的集合
12. HandlerExecutionChain handler = mapping.getHandler(request);
13. 
14. if (handler != null) {
15. return handler;
16.                 }
17.             }
18.         }
19. 
20. return null;
21.     }

自定义的mapping都在RequestMappingHandlerMapping 。

image.png

然后进入 Object handler = this.getHandlerInternal(request);。

1. public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
2. //主要方法
3.         Object handler = this.getHandlerInternal(request);
4. if (handler == null) {
5.             handler = this.getDefaultHandler();
6.         }
7. // 如果还是没有则返回 这时候 DispatcherServlet会返回 404
8. if (handler == null) {
9. return null;
10.         } else {
11. // 如果返回的处理器是字符串 则认为它是一个beanName
12. if (handler instanceof String) {
13.                 String handlerName = (String)handler;
14. // 通过beanName从IOC容器中获取相应的处理器
15.                 handler = this.obtainApplicationContext().getBean(handlerName);
16.             }
17. // 下面是将处理器 和 拦截器封装成处理器执行链
18.             HandlerExecutionChain executionChain = this.getHandlerExecutionChain(handler, request);
19. if (this.logger.isTraceEnabled()) {
20. this.logger.trace("Mapped to " + handler);
21.             } else if (this.logger.isDebugEnabled() && !request.getDispatcherType().equals(DispatcherType.ASYNC)) {
22. this.logger.debug("Mapped to " + executionChain.getHandler());
23.             }
24. 
25. if (CorsUtils.isCorsRequest(request)) {
26.                 CorsConfiguration globalConfig = this.corsConfigurationSource.getCorsConfiguration(request);
27.                 CorsConfiguration handlerConfig = this.getCorsConfiguration(handler, request);
28.                 CorsConfiguration config = globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig;
29.                 executionChain = this.getCorsHandlerExecutionChain(request, executionChain, config);
30.             }
31. // 返回处理器执行链
32. return executionChain;
33.         }
34.     }

之后再进入getHandlerInternal。

1. protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
2. //请求的路径
3.         String lookupPath = this.getUrlPathHelper().getLookupPathForRequest(request);
4. this.mappingRegistry.acquireReadLock();
5. 
6.         HandlerMethod var4;
7. try {
8. //主要方法
9.             HandlerMethod handlerMethod = this.lookupHandlerMethod(lookupPath, request);
10.             var4 = handlerMethod != null ? handlerMethod.createWithResolvedBean() : null;
11.         } finally {
12. this.mappingRegistry.releaseReadLock();
13.         }
14. 
15. return var4;
16.     }

之后再HandlerMethod handlerMethod = this.lookupHandlerMethod(lookupPath, request); 在类中 通过request中的mapping在this.mappingRegistry中获取这个bean的所有信息。

1. @Nullable
2. protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
3.         List<AbstractHandlerMethodMapping<T>.Match> matches = new ArrayList();
4.         List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);
5. if (directPathMatches != null) {
6. this.addMatchingMappings(directPathMatches, matches, request);
7.         }
8. 
9. if (matches.isEmpty()) {
10. this.addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, request);
11.         }
12. 
13. if (!matches.isEmpty()) {
14.             Comparator<AbstractHandlerMethodMapping<T>.Match> comparator = new AbstractHandlerMethodMapping.MatchComparator(this.getMappingComparator(request));
15.             matches.sort(comparator);
16.             AbstractHandlerMethodMapping<T>.Match bestMatch = (AbstractHandlerMethodMapping.Match)matches.get(0);
17. if (matches.size() > 1) {
18. if (this.logger.isTraceEnabled()) {
19. this.logger.trace(matches.size() + " matching mappings: " + matches);
20.                 }
21. 
22. if (CorsUtils.isPreFlightRequest(request)) {
23. return PREFLIGHT_AMBIGUOUS_MATCH;
24.                 }
25. 
26.                 AbstractHandlerMethodMapping<T>.Match secondBestMatch = (AbstractHandlerMethodMapping.Match)matches.get(1);
27. if (comparator.compare(bestMatch, secondBestMatch) == 0) {
28.                     Method m1 = bestMatch.handlerMethod.getMethod();
29.                     Method m2 = secondBestMatch.handlerMethod.getMethod();
30.                     String uri = request.getRequestURI();
31. throw new IllegalStateException("Ambiguous handler methods mapped for '" + uri + "': {" + m1 + ", " + m2 + "}");
32.                 }
33.             }
34. 
35.             request.setAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE, bestMatch.handlerMethod);
36. this.handleMatch(bestMatch.mapping, lookupPath, request);
37. //多个请求会返回最佳请求
38. return bestMatch.handlerMethod;
39.         } else {
40. return this.handleNoMatch(this.mappingRegistry.getMappings().keySet(), lookupPath, request);
41.         }
42.     }

然后在进行了其他操作 加入过滤器 最终返回了handler -getHandler方法结束。

image.png

2.getHandlerAdapter

获取处理器适配器。

1. protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
2. if (this.handlerAdapters != null) {
3. Iterator var2 = this.handlerAdapters.iterator();
4. 
5. while(var2.hasNext()) {               
6. HandlerAdapter adapter = (HandlerAdapter)var2.next();
7. //和处理器映射器比对
8. if (adapter.supports(handler)) {
9. return adapter;
10.                 }
11.             }
12.         }
13. 
14. throw new ServletException("No adapter for handler [" + handler + "]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
15.     }

3.mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

调用controller方法,通过反射,调用到controller中,返回ModelAndView。

1. @Nullable
2. protected Object doInvoke(Object... args) throws Exception {
3.         ReflectionUtils.makeAccessible(this.getBridgedMethod());
4. 
5. try {
6. return this.getBridgedMethod().invoke(this.getBean(), args);
7.         } catch (IllegalArgumentException var4) {
8. this.assertTargetBean(this.getBridgedMethod(), this.getBean(), args);
9.             String text = var4.getMessage() != null ? var4.getMessage() : "Illegal argument";
10. throw new IllegalStateException(this.formatInvokeError(text, args), var4);
11.         } catch (InvocationTargetException var5) {
12.             Throwable targetException = var5.getTargetException();
13. if (targetException instanceof RuntimeException) {
14. throw (RuntimeException)targetException;
15.             } else if (targetException instanceof Error) {
16. throw (Error)targetException;
17.             } else if (targetException instanceof Exception) {
18. throw (Exception)targetException;
19.             } else {
20. throw new IllegalStateException(this.formatInvokeError("Invocation failure", args), targetException);
21.             }
22.         }
23.     }

3.总结

        1.首先调用进入servlet会调用doGet和doPost方法

        2.然后调用中DispatcherServlet的doService

        3.调用doService中的doDispatch

        4.调用doDispatch中的getHandler使用handleMapping处理器映射器 去获取HandlerExecutionChain

                     1.通过mapping去this.mappingRegistry获取到需求bean在factory中的信息

                     2.将得到的hander和过滤器放在返回对象HandlerExecutionChain

         5.获取Adapter

         6.使用Adapter 通过反射调用controller

         7.返回ModelAndView


相关文章
|
前端开发 Java 测试技术
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
本文介绍了 `@RequestParam` 注解的使用方法及其与 `@PathVariable` 的区别。`@RequestParam` 用于从请求中获取参数值(如 GET 请求的 URL 参数或 POST 请求的表单数据),而 `@PathVariable` 用于从 URL 模板中提取参数。文章通过示例代码详细说明了 `@RequestParam` 的常用属性,如 `required` 和 `defaultValue`,并展示了如何用实体类封装大量表单参数以简化处理流程。最后,结合 Postman 测试工具验证了接口的功能。
1183 0
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestBody
`@RequestBody` 是 Spring 框架中的注解,用于将 HTTP 请求体中的 JSON 数据自动映射为 Java 对象。例如,前端通过 POST 请求发送包含 `username` 和 `password` 的 JSON 数据,后端可通过带有 `@RequestBody` 注解的方法参数接收并处理。此注解适用于传递复杂对象的场景,简化了数据解析过程。与表单提交不同,它主要用于接收 JSON 格式的实体数据。
1800 0
|
前端开发 Java 微服务
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@PathVariable
`@PathVariable` 是 Spring Boot 中用于从 URL 中提取参数的注解,支持 RESTful 风格接口开发。例如,通过 `@GetMapping(&quot;/user/{id}&quot;)` 可以将 URL 中的 `{id}` 参数自动映射到方法参数中。若参数名不一致,可通过 `@PathVariable(&quot;自定义名&quot;)` 指定绑定关系。此外,还支持多参数占位符,如 `/user/{id}/{name}`,分别映射到方法中的多个参数。运行项目后,访问指定 URL 即可验证参数是否正确接收。
1206 0
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestMapping
@RequestMapping 是 Spring MVC 中用于请求地址映射的注解,可作用于类或方法上。类级别定义控制器父路径,方法级别进一步指定处理逻辑。常用属性包括 value(请求地址)、method(请求类型,如 GET/POST 等,默认 GET)和 produces(返回内容类型)。例如:`@RequestMapping(value = &quot;/test&quot;, produces = &quot;application/json; charset=UTF-8&quot;)`。此外,针对不同请求方式还有简化注解,如 @GetMapping、@PostMapping 等。
1401 0
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RestController
本文主要介绍 Spring Boot 中 MVC 开发常用的几个注解及其使用方式,包括 `@RestController`、`@RequestMapping`、`@PathVariable`、`@RequestParam` 和 `@RequestBody`。其中重点讲解了 `@RestController` 注解的构成与特点:它是 `@Controller` 和 `@ResponseBody` 的结合体,适用于返回 JSON 数据的场景。文章还指出,在需要模板渲染(如 Thymeleaf)而非前后端分离的情况下,应使用 `@Controller` 而非 `@RestController`
774 0
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
前端开发 Java API
Spring Cloud Gateway Server Web MVC报错“Unsupported transfer encoding: chunked”解决
本文解析了Spring Cloud Gateway中出现“Unsupported transfer encoding: chunked”错误的原因,指出该问题源于Feign依赖的HTTP客户端与服务端的`chunked`传输编码不兼容,并提供了具体的解决方案。通过规范Feign客户端接口的返回类型,可有效避免该异常,提升系统兼容性与稳定性。
1099 0
|
SQL Java 数据库连接
Spring、SpringMVC 与 MyBatis 核心知识点解析
我梳理的这些内容,涵盖了 Spring、SpringMVC 和 MyBatis 的核心知识点。 在 Spring 中,我了解到 IOC 是控制反转,把对象控制权交容器;DI 是依赖注入,有三种实现方式。Bean 有五种作用域,单例 bean 的线程安全问题及自动装配方式也清晰了。事务基于数据库和 AOP,有失效场景和七种传播行为。AOP 是面向切面编程,动态代理有 JDK 和 CGLIB 两种。 SpringMVC 的 11 步执行流程我烂熟于心,还有那些常用注解的用法。 MyBatis 里,#{} 和 ${} 的区别很关键,获取主键、处理字段与属性名不匹配的方法也掌握了。多表查询、动态
557 0
|
JSON 前端开发 Java
第05课:Spring Boot中的MVC支持
第05课:Spring Boot中的MVC支持
577 0
|
SQL Java 数据库连接
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
1162 29