The DispatcherServlet
简单介绍Spring MVC的概念性东西
Spring MVC 中的请求工作流程:
DispatcherServlet就是一个真实的Servlet。
下面介绍两种常见的配置Dispatcher方案
1.spring framework称为典型的配置方式(Typical context hierarchy in Spring Web MVC)
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/example/*</url-pattern>
</servlet-mapping>
</web-app>
因为这里是相当与有两个Context,一个自然就是ContextLoaderListener的Context(尽管在上面的配置中没有体现) ,另一个是DispatcherServlet的。
2.单根上下文的方式(Single root context in Spring Web MVC)
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/root-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!--不可以不设置,但是可以为空-->
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
你可以使用RequestContextUtils 类的静态方法得到WebApplicationContext,从而也就可以得到容器的所有Bean.
通过下面的简单配置,我们就可以使用@Controller、@RequestMapping、@RequestParam、 @PathVariable、@ResponseBody等注解进行开发。
<mvc:annotation-driven ></mvc:annotation-driven>
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.ainoties"></context:component-scan>
但是,我们并没有看到Dispatcher是如何工作的,Controller(就是我们的@Controller类)、HandlerMap、HandlerAdapter、ViewResolver是如何工作的,什么时候被加载至容器呢?
引用官方的说法:
The Spring DispatcherServlet uses special beans to process requests and render the appropriate views. These beans are part of Spring MVC. You can choose which special beans to use by simply configuring one or more of them in the WebApplicationContext. However, you don’t need to do that initially since Spring MVC maintains a list of default beans to use if you don’t configure any.
Spring DispatcherServlet 使用指定的Beans处理请求和渲染合适的视图.这些Beans是Spring MVC 的一部分。你可以在WebApplicatioContext中通过简单地配置指定一个或者多个这个的Beans。然而,你并不需要这样初始化,如果你不进行任何配置,Spring MVC维护了一组默认的Beans供你使用。
具体有哪些默认项呢?
在Spring文档中提到:
这些默认配置都在包路径:org.springframework.web.servlet
文件名:DispatcherServlet.properties