该文章基于《Spring源码深度解析》撰写,感谢郝佳老师的奉献
SpringMVC是基于Servlet功能实现的,通过带有Servlet接口的DispatcherServlet来封装核心功能,控制器则由实现了Controller接口的类,SpringMVC解决的痛点有三个:
(1)将Web页面的请求传给服务器
(2)根据不同的请求处理不同的逻辑页面
(3)返回处理结果数据并跳转页面
Spring+SpringMVC开发的时候配置文件一般有
(1)web.xml(必须)
必须的原因在于:配置contexLoadListener,配置DispatcherServlet拦截请求
(2)applicationContext.xml(非必需,可以用来配置InternalResourceViewResolver来给返回的页面加上前缀进行试图查找)
(3)model(pojo,非必需)
(4)controller(继承AbstractController,用于处理Web请求)
(5)视图(可以由jsp或其他试图框架完成)
(6)Spring-servlet.xml(非必需,一般用于模块化开发)
现在先从最开始的web.xml文件进行分析,我们首先配置了contextConfigLocation如下所示:
<listener>
<listener-class>org.Springframework.web.context.ContextLoaderListener</listener-class>
</listener>
这个类的继承结构如下所示:
上图中的ServletContextListener该类位于servlet-api.jar包中(再tomcat的自带lib中可以找到)
ContextLoaderListener实现了ServletContextListener接口,该接口保证了在能够为客户端提供服务之前向ServletContext中添加任何对象。每个Web应用都有一个ServletContext与之相关联,启动时被创建,关闭时被销毁,并且ServletContext在全局范围内有效。ServletContextListener的核心逻辑就是初始化WebApplicationContext实例并放入ServletContext中。
我们之所以使用了ContextLoaderListener是为了避免下面这种硬编码配置:
ApplicationContext ac = new ClassPathXmlApplecation("applicationContext.xml")
再来说说ContextLoaderListener的实际步骤是:
(1)webApplication存在性验证(配置中只能有一个ServletContextListener接口,验证的方法就是检查该属性是否存在)
(2)创建webApplication实例
(3)将属性注入(例如contextConfigLocation)webApplication
(4)将实例记录到servletContext中
(5)映射当前的类加载器与创建的实例到全局变量currentContextPerThread中
讲完了ContextLoaderListener再来讲讲web.xml中另一个重要配置DispatcherServlet,对于DispatcherServlet的配置如下所示:
<<