对于最新的稳定版本,请使用 Spring Framework 6.2.0! |
DispatcherServlet 的
Spring MVC 与许多其他 Web 框架一样,是围绕前端控制器设计的
模式,其中 CENTRALServlet
这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 并覆盖特定方法
(请参阅 Context Hierarchy 下的示例)。 |
对于编程使用案例,GenericWebApplicationContext 可用作
替代AnnotationConfigWebApplicationContext .请参阅GenericWebApplicationContext javadoc 了解详细信息。 |
以下示例web.xml
configuration 注册并初始化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 遵循不同的初始化 Sequences。而不是挂接
Servlet 容器的生命周期中,Spring Boot 使用 Spring 配置来
bootstrap 本身和嵌入式 Servlet 容器。Filter 和Servlet 声明
在 Spring 配置中检测到并注册到 Servlet 容器中。
有关更多详细信息,请参阅 Spring Boot 文档。 |