DispatcherServlet

與許多其他 Web 框架一樣,Spring MVC 圍繞前端控制器模式設計,其中一箇中央的 Servlet,即 DispatcherServlet,提供了一個共享的請求處理演算法,而實際工作則由可配置的委託元件執行。這種模型非常靈活,支援多種多樣的工作流。

DispatcherServlet,與任何 Servlet 一樣,需要根據 Servlet 規範透過 Java 配置或在 web.xml 中進行宣告和對映。反過來,DispatcherServlet 使用 Spring 配置來發現請求對映、檢視解析、異常處理以及更多功能所需的委託元件。

以下 Java 配置示例註冊並初始化了 DispatcherServlet,該 Servlet 會被 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 容器。Spring 配置中檢測到 FilterServlet 聲明後會註冊到 Servlet 容器中。有關更多詳細資訊,請參閱Spring Boot 文件