此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10spring-doc.cadn.net.cn

DispatcherServlet

Spring MVC 和许多其他 Web 框架一样,是围绕前端控制器设计的 模式,其中中心ServletDispatcherServlet,提供共享算法 用于请求处理,而实际工作由可配置的委托组件执行。 该模型灵活并支持多种工作流程。spring-doc.cadn.net.cn

DispatcherServlet,与任何Servlet,需要根据 使用 Java 配置或在web.xml. 反过来,DispatcherServlet使用 Spring 配置来发现 请求映射、视图解析、异常所需的委托组件 处理,等等spring-doc.cadn.net.cn

以下 Java 配置示例将 这DispatcherServlet,由 Servlet 容器自动检测 (参见 Servlet 配置):spring-doc.cadn.net.cn

public class MyWebApplicationInitializer implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext servletContext) {

		// Load Spring web application configuration
		AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
		context.register(AppConfig.class);

		// Create and register the DispatcherServlet
		DispatcherServlet servlet = new DispatcherServlet(context);
		ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
		registration.setLoadOnStartup(1);
		registration.addMapping("/app/*");
	}
}
class MyWebApplicationInitializer : WebApplicationInitializer {

	override fun onStartup(servletContext: ServletContext) {

		// Load Spring web application configuration
		val context = AnnotationConfigWebApplicationContext()
		context.register(AppConfig::class.java)

		// Create and register the DispatcherServlet
		val servlet = DispatcherServlet(context)
		val registration = servletContext.addServlet("app", servlet)
		registration.setLoadOnStartup(1)
		registration.addMapping("/app/*")
	}
}
除了直接使用 ServletContext API 之外,您还可以扩展AbstractAnnotationConfigDispatcherServletInitializer并覆盖特定方法 (请参阅上下文层次结构下的示例)。
对于编程用例,一个GenericWebApplicationContext可以用作 替代AnnotationConfigWebApplicationContext.请参阅GenericWebApplicationContextjavadoc 了解详情。

以下示例web.xml配置寄存器并初始化DispatcherServlet:spring-doc.cadn.net.cn

<web-app>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/app-context.xml</param-value>
	</context-param>

	<servlet>
		<servlet-name>app</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>app</servlet-name>
		<url-pattern>/app/*</url-pattern>
	</servlet-mapping>

</web-app>
Spring Boot遵循不同的初始化顺序。而不是钩住 Servlet 容器的生命周期,Spring Boot 使用 Spring 配置来 bootstrap 本身和嵌入式 Servlet 容器。FilterServlet声明 在 Spring 配置中检测到并注册到 Servlet 容器中。 有关更多详细信息,请参阅 Spring Boot 文档