DispatcherServlet

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>
  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值