DispatcherServlet
Spring MVC 和许多其他 Web 框架一样,是围绕前端控制器模式设计的,其中中央 Servlet(DispatcherServlet)为请求处理提供共享算法,而实际工作由可配置的委托组件执行。该模型非常灵活,支持多种工作流程。
与任何 Servlet 一样,DispatcherServlet 需要根据 Servlet 规范使用 Java 配置或在 web.xml中声明和映射。反过来,DispatcherServlet 使用 Spring 配置来发现它需要的委托组件,用于请求映射、视图分辨率、异常处理等。
以下 Java 配置示例注册并初始化 DispatcherServlet,Servlet 容器会自动检测到该 DispatcherServlet(请参阅 Servlet Config):
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/*");
}
}
除了直接使用 ServletContext API 之外,您还可以扩展 AbstractAnnotationConfigDispatcherServletInitializer 并覆盖特定方法(请参阅 Context Hierarchy 下的示例)。
For programmatic use cases, a GenericWebApplicationContext can be used as an alternative to AnnotationConfigWebApplicationContext. See the GenericWebApplicationContext javadoc for details.
对于编程用例,GenericWebApplicationContext 可以用作 AnnotationConfigWebApplicationContext 的替代方法。有关详细信息,请参阅 GenericWebApplicationContext javadoc。
以下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>