DispatcherServlet

Spring MVC,与其他许多 Web 框架一样,围绕前端控制器模式设计,其中一个核心 Servlet,即 DispatcherServlet,提供了一个用于请求处理的共享算法,而实际工作则由可配置的委托组件执行。此模型灵活且支持多样化的工作流。

DispatcherServlet,作为任何 Servlet,需要根据 Servlet 规范通过使用 Java 配置或在 web.xml 中进行声明和映射。反过来,DispatcherServlet 使用 Spring 配置来发现其请求映射、视图解析、异常处理以及更多所需的委托组件。

以下 Java 配置示例注册并初始化了 DispatcherServlet,它由 Servlet 容器自动检测(参见Servlet 配置

  • Java

  • Kotlin

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 的替代方案。有关详细信息,请参阅 GenericWebApplicationContext 的 javadoc。

以下 web.xml 配置示例注册并初始化了 DispatcherServlet

<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 遵循不同的初始化序列。Spring Boot 不会介入 Servlet 容器的生命周期,而是使用 Spring 配置来引导自身和嵌入式 Servlet 容器。FilterServlet 声明在 Spring 配置中被检测到并注册到 Servlet 容器中。有关更多详细信息,请参见 Spring Boot 文档
© . This site is unofficial and not affiliated with VMware.