|
对于最新稳定版本,请使用 Spring Framework 7.0.6! |
DispatcherServlet
Spring MVC 与其他许多 Web 框架一样,围绕前端控制器(front controller)模式进行设计,其中由一个核心的 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 采用了一种不同的初始化顺序。它不是挂钩到 Servlet 容器的生命周期中,而是利用 Spring 配置来引导自身以及内嵌的 Servlet 容器。Filter 和 Servlet 的声明会在 Spring 配置中被检测到,并注册到 Servlet 容器中。
更多详细信息,请参阅
Spring Boot 文档。 |