參考:https://docs.spring.io/spring/docs/5.2.7.RELEASE/spring-framework-reference/web.html
Spring Web MVC是在Servlet API上構建的原始Web框架,他從一開始就包含在Spring框架中。正式的名稱Spring Web MVC來自於它的源模塊(Spring -webmvc),但更常見的名稱是Spring MVC
與許多其他web框架一樣,Spring MVC是圍繞前端控制器模式設計的,其中中心Servlet DispatcherServlet爲請求處理提供共享算法,而實際工作是由可配置的委託組件執行的。這個模型非常靈活,並且支持不同的工作流
與任何Servlet一樣,DispatcherServlet需要通過使用Java配置或web.xml根據Servlet規範聲明和映射。然後,DispatcherServlet使用Spring配置來發現請求映射、視圖解析、異常處理等所需的委託組件。
下面的Java配置示例註冊並初始化DispatcherServlet,它由Servlet容器自動檢測
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletCxt) {
// Load Spring web application configuration
AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
ac.register(AppConfig.class);
ac.refresh();
// Create and register the DispatcherServlet
DispatcherServlet servlet = new DispatcherServlet(ac);
ServletRegistration.Dynamic registration = servletCxt.addServlet("app", servlet);
registration.setLoadOnStartup(1);
registration.addMapping("/app/*");
}
}
除了直接使用ServletContext API,您還可以擴展AbstractAnnotationConfigDispatcherServletInitializer並覆蓋特定的方法
下面的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>
SpringBoot遵循不同的初始化順序。Spring Boot沒有連接到Servlet容器的生命週期中,而是使用Spring配置來引導自身和嵌入的Servlet容器。過濾器和Servlet聲明在Spring配置中檢測到之後並註冊到Servlet容器中
Context Hierarchy
DispatcherServlet需要一個WebApplicationContext(ApplicationContext的擴展)用於自己的配置。WebApplicationContext有一個到ServletContext和與之關聯的Servlet的鏈接。它還綁定到ServletContext,以便應用程序可以使用RequestContextUtils上的靜態方法來查找WebApplicationContext,如果它們需要訪問它的話