在web.xml中,可以找到这么一段配置文件,它的作用是将DispatchServlet作为一个servlet加载到servlet容器中 其中,是将某一类请求转交给这个servlet进行处理

<servlet><servlet-name>SpringMVC</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup>//是否开启异步支持<!--<async-supported>true</async-supported>-->
</servlet>
<servlet-mapping><servlet-name>SpringMVC</servlet-name><url-pattern>/</url-pattern>
</servlet-mapping>
复制代码

然后我们开始解析一下DispatchServlet具体做了些什么事情

1)加载DispatcherServlet.properties中的属性

private static final String DEFAULT_STRATEGIES_PATH = "DispatcherServlet.properties";...static {// Load default strategy implementations from properties file.// This is currently strictly internal and not meant to be customized// by application developers.try {ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherServlet.class);defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);}catch (IOException ex) {throw new IllegalStateException("Could not load 'DispatcherServlet.properties': " + ex.getMessage());}
}
复制代码

找到DispatcherServlet.properties,其中内容如下

# Default implementation classes for DispatcherServlet's strategy interfaces.
# Used as fallback when no matching beans are found in the DispatcherServlet context.
# Not meant to be customized by application developers.org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolverorg.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolverorg.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMappingorg.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapterorg.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver,\org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolverorg.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslatororg.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolverorg.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManager
复制代码

所以我们可以知道,这个DispatcherServlet.properties的作用是将默认实现类的路径以键值对的形式加载进来 LocaleResolver(本地化解析器,AcceptHeaderLocaleResolver) ThemeResolver(主题解析器,FixedThemeResolver) HandlerMapping(映射处理器,BeanNameUrlHandlerMapping) HandlerAdapter(处理适配器,多个) ViewResolver(视图解析器,InternalResourceViewResolver) RequestToViewNameTranslator(将请求名称转化为视图名称,DefaultRequestToViewNameTranslator)

2)初始化加载SpringMVC框架下需要配置的基本的bean

protected void initStrategies(ApplicationContext context) {initMultipartResolver(context);initLocaleResolver(context);initThemeResolver(context);initHandlerMappings(context);initHandlerAdapters(context);initHandlerExceptionResolvers(context);initRequestToViewNameTranslator(context);initViewResolvers(context);initFlashMapManager(context);
}
复制代码

这里的作用是将SpringMVC框架所需的各个基本的bean初始化,并加载到容器中

3)重写doService()方法

DispatchServlet实际上继承于FrameworkServlet,并且在其具体实现中重写了doService()方法。 doService()主要是将一些全局属性set到request中,具体的请求处理则调用并在doDispatch()中处理

4)doDipatch()将请求处理后转发到Controller

/**
* Process the actual dispatching to the handler.
* <p>The handler will be obtained by applying the servlet's HandlerMappings in order.
* The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters
* to find the first that supports the handler class.
* <p>All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers
* themselves to decide which methods are acceptable.
* @param request current HTTP request
* @param response current HTTP response
* @throws Exception in case of any kind of processing failure
*/
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {//获取当前要处理的requestHttpServletRequest 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);// Determine handler for the current request.//获取HandlerExecutionChain,其中包含了private HandlerInterceptor[] interceptors,即拦截器的一个数组mappedHandler = getHandler(processedRequest);if (mappedHandler == null || mappedHandler.getHandler() == null) {noHandlerFound(processedRequest, response);return;}// Determine handler adapter for the current request.//获取HandlerAdapterHandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());// Process last-modified header, if supported by the handler.//从request中获取HTTP请求方法String method = request.getMethod();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;}}//如果有拦截器,则处理其前置方法preHandleif (!mappedHandler.applyPreHandle(processedRequest, response)) {return;}// Actually invoke the handler.//返回处理后的modelViewmv = ha.handle(processedRequest, response, mappedHandler.getHandler());//判断是否是异步请求if (asyncManager.isConcurrentHandlingStarted()) {return;}//如果view为空,返回一个默认的viewapplyDefaultViewName(processedRequest, mv);//处理拦截器的后置方法postHandlemappedHandler.applyPostHandle(processedRequest, response, mv);}catch (Exception ex) {dispatchException = ex;}processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);}catch (Exception ex) {triggerAfterCompletion(processedRequest, response, mappedHandler, ex);}catch (Error err) {triggerAfterCompletionWithError(processedRequest, response, mappedHandler, 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);}}}
}
复制代码

理解SpringMVC-------DispatchServlet相关推荐

  1. springmvc DispatchServlet初始化九大加载策略(一)

    由于篇幅较长,因此分三篇进行讲解: springmvc DispatchServlet初始化九大加载策略(一) springmvc DispatchServlet初始化九大加载策略(二) spring ...

  2. springmvc 传对象报400_源码导读:深入理解SpringMVC报400时的流程

    相信很多同学都了解过(或者面试前都会复习过)springMVC的执行流程,如下图: 网图 转载请注明出处:Michael孟良 这里我想细节地理解下springMVC报400(也就是上图第5步拿到Han ...

  3. springmvc DispatchServlet初始化九大加载策略(二)

    4. initHandlerMappings 请求分发 HandlerMappings是一个List<HandlerMapping>类型数据,也就是说初始化可以存放多种Mapping,和其 ...

  4. 深入理解springMVC

    什么是spring MVC Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面.Spring 框架提供了构建 Web 应用程序的全功能 MV ...

  5. 简单理解SpringMVC的三层结构顺序MCV以及ModelAndView的使用

    MVC三层结构 (M->C->V) requset–>中心总控制器(DispatcherServlet) 中心控制器接收到用户请求后:将请求转发到HandlerMapping (方法 ...

  6. SpringMVC原理分析之一MVC框架

    本篇博文以MVC原理为基础,讲解了MVC的架构概念 需要解决的问题,以及使用SpringMVC搭建项目示例让读者了解MVC架构的优秀实现者SpringMVC框架,最后以DispatcherServle ...

  7. 面试官问你 SpringMVC 的工作原理,你还不知道吗?

    SpringMVC的工作原理图: SpringMVC流程 1. 用户发送请求至前端控制器DispatcherServlet. 2. DispatcherServlet收到请求调用HandlerMapp ...

  8. SpringMVC工作原理

    一:SpringMVC的工作原理图 二:SpringMVC流程 用户发送请求至前端控制器DispatcherServlet. DispatcherServlet收到请求调用HandlerMapping ...

  9. SpringMVC学习(二)——SpringMVC架构及组件(及其运行原理)

    相信大家通过前文的学习,已经对SpringMVC这个框架多少有些理解了.还记得上一篇文章中SpringMVC的处理流程吗?    这个图大致描述了SpringMVC的整个处理流程,这个流程图还是相对来 ...

  10. Spring、SpringMVC、SpringBoot、SpringCloud的联系和区别

    一. 上一篇文章刚刚简单介绍了spring框架,下面我将介绍一下Spring,SpringMVC,SpringBoot,SpringCloud的联系和区别. 首先先简单介绍一下各个框架. Spring ...

最新文章

  1. HP-UX磁带备份错误收集
  2. java2d游戏代码_Java 2D游戏图形
  3. OpenKruise 如何实现 K8s 社区首个规模化镜像预热能力
  4. 理念高大上的智慧社区,要落地还得俯下身解决四个现实问题
  5. 3.顶点外扩方法实现的描边shader
  6. MySQL 8.0 ROLE管理
  7. 【英语学习】【WOTD】gormless 释义/词源/示例
  8. 2017/09/15
  9. python爬取人口数据_爬取人口数据
  10. KITTI数据集Raw Data与Ground Truth序列00-10的对应关系,以及对应的标定参数
  11. 对抗神经网络 (GAN) 的深入了解
  12. maven报错:Failure to transfer xxx.jar from xxx was cached in the local repository.
  13. java反射获取一个对象中属性(field)的值
  14. ASP.NET 基于asp.net设计项目框架
  15. 推销计算机作文题目怎么写,怎样让作文题目吸引人 吸引人的作文题目怎么写...
  16. 揭秘中国网络虚假新闻“制造器”,看传播者如何操纵操纵大众舆论?
  17. 《小目标目标检测的解决方法及方式》
  18. 诺基亚n1 android 6.0,数据解读诺基亚N1:安卓平板王者之争
  19. Race_Condition实验
  20. java毕业2年如何做到月薪2万

热门文章

  1. HTML5如何添加图片遮罩,带有HTML5画布的putImageData的遮罩?
  2. FreeSWITCH 总体架构
  3. windows下连接smb服务器
  4. Tomcat+nginx+keepalived+memcached实现双VIP负载均衡及Session会话保持
  5. linux系统web站点设置-http基础设置
  6. 2017 Multi-University Training Contest - Team 2——HDU6045HDU6047HDU6055
  7. 黑马程序员-----内部类、匿名内部类应用
  8. ORA-06502:PL/SQL :numberic or value error: character string buffer too small
  9. 简陋,山寨,Everything,桌面搜索,原理,源码
  10. SQL Lite on NHibernate