ssm在項目運行時,首先會加載web.xml
其中web.xml中加載順序:context-param -> listener -> filter -> servlet -> interceptor(同類級別按照順序執行)
1.ServletContext
首先我們說到ServletContext,ServletContext是一個Web應用的全局上下文,可以理解為整個Web應用的全局變量,項目中的所有方法皆可以獲取ServletContext。
說到ServletContext,就到說到所有web項目的web.xml,下面我們先貼出web.xml的一部分配置:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>listener.SessionListener</listener-class>
</listener>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<filter>
<filter-name>sessionFilter</filter-name>
<filter-class>web.filter.SessionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sessionFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
上面貼出的就是web.xml的部分配置,在這里我們首先講解下web項目啟動的加載順序:
以Tomcat舉例,啟動Tomcat之后,首先會加載web.xml文件:
a)容器首先讀取web.xml中的<context-param>的配置內容和<listener>標簽中配置項;
b)緊接着實例化ServletContext對象,並將<context-param>配置的內容轉化為鍵值傳遞給ServletContext;
c)創建<listener>配置的監聽器的類實例,並且啟動監聽;
d)隨后調用listener的contextInitialized(ServletContextEvent args)方法,ServletContext = ServletContextEvent.getServletContext();
此時你可以通過ServletContext獲取context-param配置的內容並可以加以修改,此時Tomcat還沒完全啟動完成。
e)后續加載配置的各類filter;
f)最后加載servlet;
最后的結論是:web.xml中配置項的加載順序是context-param=>listener=>filter=>servlet,配置項的順序並不會改變加載順序,但是同類型的配置項會應該加載順序,servlet中也可以通過load-on-startup來指定加載順序。
ServletContext中的屬性所有的servlet皆可以使用ServletContext.
2.ApplicationContext
首先介紹下applicationContext,applicationContext是spring的BeanFactory的實現類:

ApplicationContext接口的繼承關系如上面的截圖,ApplicationContext是如何產生的呢,這里我們看之前的web.xml中的
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
繼承關系如左圖
我們看看是如何初始化的
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
throw new IllegalStateException(
"Cannot initialize context because there is already a root application context present - " +
"check whether you have multiple ContextLoader* definitions in your web.xml!");
}
Log logger = LogFactory.getLog(ContextLoader.class);
servletContext.log("Initializing Spring root WebApplicationContext");
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis();
try {
// Store context in local instance variable, to guarantee that
// it is available on ServletContext shutdown.
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent ->
// determine parent for root web application context, if any.
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
servletContext.setAttribute(c, this.context);
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl == ContextLoader.class.getClassLoader()) {
currentContext = this.context;
}
else if (ccl != null) {
currentContextPerThread.put(ccl, this.context);
}
if (logger.isDebugEnabled()) {
logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
}
if (logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
}
return this.context;
}
catch (RuntimeException ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
catch (Error err) {
logger.error("Context initialization failed", err);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
throw err;
}
}
代碼中加粗的部分就是講WebApplicationContext以WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE為key保存到ServletContext中,所以我們在需要獲取時,可以根據request.getSession().
getAttribute("WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE")來獲取WebApplicationContext.
所以WebApplicationContext依賴於ServletContext,ApplicationContext存儲了Spring中所有的Bean,
但是我們常規的Springmvc項目一般除了applicationContext.xml之外還有springmvc.xml,兩個配置文件會對應兩個ApplicationContext,springmvc的ApplicationContext中可以調用applicationContext.xml的ApplciationContext。
3.獲取WebApplication的幾種方式
a)request.getSession().getServletContext().getAttribute("org.springframework.web.context.WebApplicationContext.ROOT")
b)實現ApplicationContextAware接口
public interface ApplicationContextAware {
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
