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.