SpringMVC工作原理及DispatcherServlet源码解析

本文主要是介绍SpringMVC工作原理及DispatcherServlet源码解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、SpringMVC整体流程

先来看看SpringMVC的工作流程图:

下面来看看每一步都是在做什么:

第一步:用户发起request请求,请求至DispatcherServlet前端控制器。

第二步:DispatcherServlet前端控制器请求HandlerMapping处理器映射器查找Handler。

              DispatcherServlet:前端控制器,相当于中央调度器,各各组件都和前端控制器进行交互,降低了各组件之间耦合度。

第三步:HandlerMapping处理器映射器,根据url及一些配置规则(xml配置、注解配置)查找Handler,将Handler返回给                          DispatcherServlet前端控制器。

第四步:DispatcherServlet前端控制器调用适配器执行Handler,有了适配器通过适配器去扩展对不同Handler执行方式(比如:                原始servlet开发,注解开发)

第五步:适配器执行Handler。Handler是后端控制器,当成模型。

第六步:Handler执行完成返回ModelAndView

              ModelAndView是springmvc的一个对象,对Modelview进行封装。

第七步:适配器将ModelAndView返回给DispatcherServlet

第八步:DispatcherServlet调用视图解析器进行视图解析,解析后生成view。视图解析器根据逻辑视图名解析出真正的视图。

              View:springmvc视图封装对象,提供了很多view,比如:jsp、freemarker、pdf、excel。

第九步:ViewResolver视图解析器给前端控制器返回view

第十步:DispatcherServlet调用view的渲染视图的方法,将模型数据填充到request域 。

第十一步:DispatcherServlet向用户响应结果(jsp页面、json数据。)

在这里面有几个组件要说一下:

  • DispatcherServlet:前端控制器,由springmvc提供
  • HandlerMappting:处理器映射器,由springmvc提供
  • HandlerAdapter:处理器适配器,由springmvc提供
  • Handler:处理器,需要程序员开发
  • ViewResolver:视图解析器,由springmvc提供
  • View:真正视图页面需要由程序编写

 由上面springMVC的工作流程图我们可以知道,其实springMVC的核心就是DispatcherServlet,所以接下来主要就是通过源码来看看DispatcherServlet是怎么工作的。

FROM 《SpringMVC - 运行流程图及原理分析》

流程示意图

代码序列图


FROM 《看透 Spring MVC:源代码分析与实践》 P123

流程示意图

 

二、服务流程

一般而言,Servlet有一个服务方法 doService来为HTTP请求提供服务(如参照前面的servlet源码解析), DispatcherServlet也是如此,它的 doService 方法如下面代码所示:

//将DispatcherServlet特定的请求转发给doDispatch处理
@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {if (logger.isDebugEnabled()) {String resumed = WebAsyncUtils.getAsyncManager(request).hasConcurrentResult() ? " resumed" : "";logger.debug("DispatcherServlet with name '" + getServletName() + "'" + resumed +" processing " + request.getMethod() + " request for [" + getRequestUri(request) + "]");}// 快照处理,使用快照可以更快响应用户请求Map<String, Object> attributesSnapshot = null;if (WebUtils.isIncludeRequest(request)) {attributesSnapshot = new HashMap<String, Object>();Enumeration<?> attrNames = request.getAttributeNames();while (attrNames.hasMoreElements()) {String attrName = (String) attrNames.nextElement();if (this.cleanupAfterInclude || attrName.startsWith("org.springframework.web.servlet")) {attributesSnapshot.put(attrName, request.getAttribute(attrName));}}}// 设置Web IOC容器request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());//设置国际化request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);//主题属性request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);//主题源属性request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);if (inputFlashMap != null) {request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));}request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);try {//处理分发doDispatch(request, response);}finally {if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {// Restore the original attribute snapshot, in case of an include.if (attributesSnapshot != null) {restoreAttributesAfterInclude(request, attributesSnapshot);}}}
}

由上面的代码和注释可以看到,doService先对HTTP请求进行一些处理,然后设置一些属性,最后所有的流程都集中在了 doDispatch 方法中。所以接下来我们继续看doDispatch方法:

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {HttpServletRequest processedRequest = request;HandlerExecutionChain mappedHandler = null;boolean multipartRequestParsed = false;WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);try {//模型和视图ModelAndView mv = null;//错误处理Exception dispatchException = null;try {//文件上传处理解析器processedRequest = checkMultipart(request);//是否为文件上传请求multipartRequestParsed = (processedRequest != request);// 获得匹配的执行链,决定处理请求的handlermappedHandler = getHandler(processedRequest);//没有处理器错误if (mappedHandler == null || mappedHandler.getHandler() == null) {noHandlerFound(processedRequest, response);return;}// 找到对应的处理器适配器(HandlerAdapter)HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());// Process last-modified header, if supported by the handler.///判断是 http 的 get 方法还是 post 方法或其他String method = request.getMethod();//如果是GET方法的处理boolean isGet = "GET".equals(method);if (isGet || "HEAD".equals(method)) {long lastModified = ha.getLastModified(request, mappedHandler.getHandler());if (logger.isDebugEnabled()) {logger.debug("Last-Modified value for [" + getRequestUri(request) + "] is: " + lastModified);}if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {return;}}//执行拦截器的事前方法,如果返回 false,则流程结束if (!mappedHandler.applyPreHandle(processedRequest, response)) {return;}// Actually invoke the handler.//执行处理器,返回 ModelAndViewmv = ha.handle(processedRequest, response, mappedHandler.getHandler());if (asyncManager.isConcurrentHandlingStarted()) {return;}//如果视图为空,给予设置默认视图的名称applyDefaultViewName(processedRequest, mv);//执行处理器拦截器的事后方法mappedHandler.applyPostHandle(processedRequest, response, mv);}catch (Exception ex) {//记录异常dispatchException = ex;}processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);}catch (Throwable ex) {//记录异常dispatchException = new NestedServletException(”Handler dispatch failed ”, err) ;}//处理请求结果,显然这里已经通过处理器得到最后的结果和视图 //如果是逻辑视图,则解析名称,否则就不解析,最后渲染视图processDispatchResult(processedRequest, response,mappedHandler, mv, dispatchException);}catch (Exception ex) {//异常处理,拦截器完成方法triggerAfterCompletion(processedRequest, response, mappedHandler, ex);}catch (Throwable err) {//错误处理triggerAfterCompletionWithError(processedRequest, response, mappedHandler, new NestedServletException (”Handler processing failed ",err)) ;}finally {//处理资源的释放if (asyncManager.isConcurrentHandlingStarted()) {// Instead of postHandle and afterCompletionif (mappedHandler != null) {//拦截器完成方法mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);}}else {// Clean up any resources used by a multipart request.//文件请求资源释放if (multipartRequestParsed) {cleanupMultipart(processedRequest);}}}}

通过源码可以看出其流程是 :
(l)通过请求找到对应的执行链,执行链包含了拦截器和开发者控制器。

(2)通过处理器找到对应的适配器。

(3)执行拦截器的事前方法,如果返回 false,则流程结束,不再处理 。

(4)通过适配器运行处理器,然后返回模型和视图。

(5)如果视图没有名称 ,则 给出默认的视图名称。

(6)执行拦截器的事后方法。

(7)处理分发请求得到的数据模型和视图的渲染。

三、处理器和执行器

在上面,我们已经了解了一个请求到达springMVC后,DispatcherServlet是怎么处理这个请求的,接下来就是看看处理器和拦截器,即DispatcherServlet的getHandler方法:

protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {for (HandlerMapping hm : this.handlerMappings) {if (logger.isTraceEnabled()) {logger.trace("Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'");}HandlerExecutionChain handler = hm.getHandler(request);if (handler != null) {return handler;}}return null;}

在启动期间, SpringMVC已经初始化了处理器映射--HandlerMappings,所以这里先根据请求找到对应的 HandlerMapping,找到 HandlerMapping 后,就把相关处理的内容转化成一个 HandlerExecutionChain 对象。

接下来就来看看HandlerExecutionChain的结构是什么样的:

public class HandlerExecutionChain {private static final Log logger = LogFactory.getLog(HandlerExecutionChain.class);//处理器,自己写的控制器(或其方法)private final Object handler;//拦截器数组private HandlerInterceptor[] interceptors;//拦截器列表private List<HandlerInterceptor> interceptorList;//当前拦截器下标,当使用数组时有效private int interceptorIndex = -1;...
}

由源码可以看出,主要是定义一些拦截器相关的属性,可以在进入控制器之前 , 运行对应的拦截器,这样就可以在进入处理器前做一些逻辑了。如果在做电商系统的时候,用户可以再未登录状态浏览商品,并加入购物车,但是如果要结算的时候,这个时候就要拦截请求,要求用户登录。这个时候就可以通过拦截器实现。接下来就来看看拦截器Handlerlnterceptor的相关方法:

public interface HandlerInterceptor {boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception;void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)throws Exception;void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception;

依据 doDispatch 方法,当preHandle方法返回为 true 的时候才会继续运行,否则就会结束流程,而在数据模型渲染视图之前调用 postHandle方法, 在流程的 finally语 句中还会调用 afterCompletion方法, 这就是处理器拦截器的内容。如果要自己做一个拦截器的话,可以实现Handlerlnterceptor接口,然后重写这三个方法,你可以在这三个方法里面加入相应的业务逻辑进行处理。

四、视图渲染

在第二点的时候,我们知道processDispatchResult对模型和视图的处理,接下来我们来看看SpringMVC是怎么实现视图渲染。

private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,HandlerExecutionChain mappedHandler, ModelAndView mv, Exception exception) throws Exception {boolean errorView = false;//处理器发生异常if (exception != null) {//视图和模型定义方面的异常if (exception instanceof ModelAndViewDefiningException) {logger.debug("ModelAndViewDefiningException encountered", exception);mv = ((ModelAndViewDefiningException) exception).getModelAndView();}//处理器的异常else {Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);mv = processHandlerException(request, response, handler, exception);errorView = (mv != null);}}//处理器是否返回视图和模型if (mv != null && !mv.wasCleared()) {//渲染视图render(mv, request, response);if (errorView) {WebUtils.clearErrorRequestAttributes(request);}}else {//视图为 null,或者已经被处理过if (logger.isDebugEnabled()) {logger.debug("Null ModelAndView returned to DispatcherServlet with name '" + getServletName() +"': assuming HandlerAdapter completed request handling");}}//是否存在并发处理if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {// Concurrent handling started during a forwardreturn;}//完成方法if (mappedHandler != null) {mappedHandler.triggerAfterCompletion(request, response, null);}}

由上面的源码可以看出,首先是先判断是否异常,如果有异常就再进一步处理是什么异常,如果没有异常就通过render方法进行进一步处理,相关逻辑也在注释中表明了,接下来就来看看render这个方法:

protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {// Determine locale for request and apply it to the response.
//国际化Locale locale = this.localeResolver.resolveLocale(request);response.setLocale(locale);View view;
//是否是逻辑视图,如果是需要转化为真实路径下的视图if (mv.isReference()) {// We need to resolve the view name.
//转化逻辑视图为真实视图view = resolveViewName(mv.getViewName(), mv.getModelInternal(), locale, request);if (view == null) {throw new ServletException("Could not resolve view with name '" + mv.getViewName() +"' in servlet with name '" + getServletName() + "'");}}
//非逻辑视图else {// No need to lookup: the ModelAndView object contains the actual View object.view = mv.getView();if (view == null) {throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " +"View object in servlet with name '" + getServletName() + "'");}}// Delegate to the View object for rendering.if (logger.isDebugEnabled()) {logger.debug("Rendering view [" + view + "] in DispatcherServlet with name '" + getServletName() + "'");}try {
//渲染视图, view 为视圈, mv.getModelInternal ()为数据模型view.render(mv.getModelInternal(), request, response);}catch (Exception ex) {if (logger.isDebugEnabled()) {logger.debug("Error rendering view [" + view + "] in DispatcherServlet with name '" +getServletName() + "'", ex);}throw ex;}}

首先是国际化的设置,然后判断是否是逻辑视图,如果是就转化它为 真实视图,或者 直接获取视图即可,最后进入视图的 render方法,将模型和视图中的数据模型传递到该方 法中去,这样就完成了视图的渲染,展示给用户。

这篇关于SpringMVC工作原理及DispatcherServlet源码解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/687127

相关文章

Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码

《Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码》:本文主要介绍Java中日期时间转换的多种方法,包括将Date转换为LocalD... 目录一、Date转LocalDateTime二、Date转LocalDate三、LocalDateTim

如何配置Spring Boot中的Jackson序列化

《如何配置SpringBoot中的Jackson序列化》在开发基于SpringBoot的应用程序时,Jackson是默认的JSON序列化和反序列化工具,本文将详细介绍如何在SpringBoot中配置... 目录配置Spring Boot中的Jackson序列化1. 为什么需要自定义Jackson配置?2.

Java中使用Hutool进行AES加密解密的方法举例

《Java中使用Hutool进行AES加密解密的方法举例》AES是一种对称加密,所谓对称加密就是加密与解密使用的秘钥是一个,下面:本文主要介绍Java中使用Hutool进行AES加密解密的相关资料... 目录前言一、Hutool简介与引入1.1 Hutool简介1.2 引入Hutool二、AES加密解密基础

MySQL中FIND_IN_SET函数与INSTR函数用法解析

《MySQL中FIND_IN_SET函数与INSTR函数用法解析》:本文主要介绍MySQL中FIND_IN_SET函数与INSTR函数用法解析,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一... 目录一、功能定义与语法1、FIND_IN_SET函数2、INSTR函数二、本质区别对比三、实际场景案例分

Go 语言中的select语句详解及工作原理

《Go语言中的select语句详解及工作原理》在Go语言中,select语句是用于处理多个通道(channel)操作的一种控制结构,它类似于switch语句,本文给大家介绍Go语言中的select语... 目录Go 语言中的 select 是做什么的基本功能语法工作原理示例示例 1:监听多个通道示例 2:带

Spring Boot项目部署命令java -jar的各种参数及作用详解

《SpringBoot项目部署命令java-jar的各种参数及作用详解》:本文主要介绍SpringBoot项目部署命令java-jar的各种参数及作用的相关资料,包括设置内存大小、垃圾回收... 目录前言一、基础命令结构二、常见的 Java 命令参数1. 设置内存大小2. 配置垃圾回收器3. 配置线程栈大小

SpringBoot实现微信小程序支付功能

《SpringBoot实现微信小程序支付功能》小程序支付功能已成为众多应用的核心需求之一,本文主要介绍了SpringBoot实现微信小程序支付功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作... 目录一、引言二、准备工作(一)微信支付商户平台配置(二)Spring Boot项目搭建(三)配置文件

解决SpringBoot启动报错:Failed to load property source from location 'classpath:/application.yml'

《解决SpringBoot启动报错:Failedtoloadpropertysourcefromlocationclasspath:/application.yml问题》这篇文章主要介绍... 目录在启动SpringBoot项目时报如下错误原因可能是1.yml中语法错误2.yml文件格式是GBK总结在启动S

鸿蒙中@State的原理使用详解(HarmonyOS 5)

《鸿蒙中@State的原理使用详解(HarmonyOS5)》@State是HarmonyOSArkTS框架中用于管理组件状态的核心装饰器,其核心作用是实现数据驱动UI的响应式编程模式,本文给大家介绍... 目录一、@State在鸿蒙中是做什么的?二、@Spythontate的基本原理1. 依赖关系的收集2.

Spring中配置ContextLoaderListener方式

《Spring中配置ContextLoaderListener方式》:本文主要介绍Spring中配置ContextLoaderListener方式,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录Spring中配置ContextLoaderLishttp://www.chinasem.cntene