DispatcherServlet 源码分析(一)

1.配置

	<listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:SpringMybatisConfiguration.xml</param-value>
	</context-param>
	
	<servlet>
		<servlet-name>dispatch</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:test-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>dispatch</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>

值得注意的是需要将MVC相关的配置提取在*-servert.xml中,将业务核心逻辑类相关配置文件放在如下配置中。

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:SpringMybatisConfiguration.xml</param-value>
	</context-param>

这么做可以有很好的分层的效果。当然也可以将所有的配置都放在DispatcherServlet中,而删除以下配置,很不推荐。

<listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:SpringMybatisConfiguration.xml</param-value>
	</context-param>

2.用途

Spring MVC的核心类。


3. 结构

DispatcherServlet extends FrameworkServlet extends HttpServletBean extends HttpServlet


4. 初始化

一般配置为servlet容器启动时就进行init:<load-on-startup>1</load-on-startup>,否则将在初次访问时进行init。


HttpServletBean.init()

FrameworkServlet.initServletBean()

FrameworkServlet.initWebApplicationContext():根据配置文件(由<param-name>contextConfigLocation</param-name>指定)初始化一个WebApplicationContext,值得注意的是该WebApplicationContext的父容器是org.springframework.web.context.ContextLoaderListener初始化的WebApplicationContext。一般来说我们会把负责业务逻辑配置文件由ContextLoaderListener来加载,将MVC相关的配置文件由DispatcherServlet来加载。实现比较好的解耦。

DispatcherServlet.onRefresh(ApplicationContext context)

DispatcherServlet.initStrategies(ApplicationContext context):完成了DispatcherServlet核心功能的装配,如果用户没有配置,则使用默认的:/org/springframework/web/servlet/DispatcherServlet.properties






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值