DispatcherServlet
Spring MVC,像许多其他Web框架一样,是围绕前端控制器模式设计的,其中中央Servlet,即DispatcherServlet,为请求处理提供了一个共享算法,而实际工作则由可配置的委托组件完成。这种模型非常灵活,支持多种工作流程。
The DispatcherServlet, as any Servlet, needs to be declared and mapped according
to the Servlet specification by using Java configuration or in web.xml.
In turn, the DispatcherServlet uses Spring configuration to discover
the delegate components it needs for request mapping, view resolution, exception
handling, 等等.
以下示例展示了程序化注册和初始化
DispatcherServlet 的过程,该过程由 Servlet 容器自动检测
(参见 Servlet 配置),以及等效的
web.xml:
-
Java
-
Kotlin
-
Xml
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/*")
}
}
<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>
除了直接使用ServletContext API,你还可以扩展AbstractAnnotationConfigDispatcherServletInitializer并重写特定方法(参见上下文层次结构下的示例)。 |
对于编程使用情况,可以使用 GenericWebApplicationContext 作为 AnnotationConfigWebApplicationContext 的替代。请参阅
GenericWebApplicationContext
javadoc 以获取详细信息。 |
Spring Boot 采用了一种不同的初始化顺序。它不依赖于 Servlet 容器的生命周期,而是使用 Spring 配置来启动自身和嵌入式 Servlet 容器。Filter 和 Servlet 声明在 Spring 配置中被检测到,并注册到 Servlet 容器中。有关详细信息,请参阅
Spring Boot 文档。 |