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 配置中检测到 Filter 和 Servlet 声明后会注册到 Servlet 容器中。有关更多详细信息,请参阅Spring Boot 文档。 |