DispatcherServlet
Spring MVC,与许多其他 Web 框架一样,是围绕前端控制器模式设计的,其中一个中央 Servlet
,即 DispatcherServlet
,为请求处理提供了一个共享算法,而实际工作则由可配置的委托组件执行。这种模型灵活且支持多种工作流。
DispatcherServlet
,作为任何 Servlet
,需要通过 Java 配置或在 web.xml
中根据 Servlet 规范进行声明和映射。反过来,DispatcherServlet
使用 Spring 配置来发现其请求映射、视图解析、异常处理以及 更多所需的委托组件。
以下 Java 配置示例注册并初始化了 DispatcherServlet
,该 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 外,你还可以扩展 |
对于编程使用场景, |
以下 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 容器。 |