1.1. DispatcherServlet
与Spring WebFlux相同
Spring MVC和许多其他Web框架一样,围绕前端控制器模式设计,其中中央Servlet DispatcherServlet为请求处理提供共享算法,而实际工作由可配置委托组件执行。 该模型非常灵活,支持多种工作流程。
DispatcherServlet与任何其他Servlet一样,需要使用Java配置或web.xml根据Servlet规范进行声明和映射。 反过来,DispatcherServlet使用Spring配置来发现请求映射,视图解析,异常处理等所需的委托组件。
下面的Java配置示例注册并初始化DispatcherServlet,它由Servlet容器自动侦测(详情请参阅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之外,您还可以使用extendAbstractAnnotationConfigDispatcherServletInitializer并覆盖特定方法(请参阅Context Hierarchy下的示例)。 |
以下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使用Spring配置来引导自身和嵌入式Servlet容器,而不是挂载到Servlet容器的生命周期。 在Spring配置中检测Filter和Servlet声明,并在Servlet容器中注册。 有关更多详细信息,请参阅Spring Boot文档。 |