細說ServletContext、WebApplicationContext、Servlet的初始化

細說ServletContext、WebApplicationContext、Servlet的初始化

瀏覽器請求發送給服務器的過程

1.瀏覽器發送http請求到web容器。比如請求發送給tomcat等web容器。

2.tomcat將http請求封裝成httpServletRequest併發送給web項目。而

Servletcontext就是tomcat給web項目創建的全局環境。他有以下特點:

  1. 全局共享數據。
  2. 包含着web.xml裏面的初始值。

1.ServletContext對象的生命週期

​ ServletContext代表是一個web應用的環境(上下文)對象,ServletContext象 內部封裝是該web應用的信息,一個web應用只有一個。

創建:該web應用被加載(服務器啓動或發佈web應用(前提,服務器啓動狀 態))

銷燬:web應用被卸載(服務器關閉,移除該web應用)

2.ServletContext的運行流程

通過一個例子來說明:

通過上面知曉:當Servlet容器啓動時會加載web.xml配置文件,並且創建一個ServletContext對象,將web.xml中的參數信息存放在ServletContext對象中。

執行流程:

web.xml在<context-param></context-param>標籤中聲明應用範圍內的初始化參數

1.啓動一個WEB項目的時候,容器(如:Tomcat)會去讀它的配置文件web.xml.讀兩個節點: <listener></listener><context-param></context-param>

2.緊接着,容器創建一個ServletContext(上下文)。在該應用內全局共享。

3.容器將<context-param></context-param>轉化爲鍵值對,並交給ServletContext.

4.容器創建<listener></listener>中的類實例,即創建監聽.該監聽器必須實現自ServletContextListener接口

5.在監聽中會有contextInitialized(ServletContextEvent event)初始化方法

在這個方法中獲得ServletContext = ServletContextEvent.getServletContext();

“context-param的值” = ServletContext.getInitParameter(“context-param的鍵”);

6.得到這個context-param的值之後,你就可以做一些操作了.注意,這個時候你的WEB項目還沒有完全啓動完成.這個動作會比所有的Servlet都要早.換句話說,這個時候,你對<context-param>中的鍵值做的操作,將在你的WEB項目完全啓動之前被執行.

web.xml中有兩種參數的定義

  1. 全局參數(ServletContext):定義在context-param標籤中
<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>
        classpath:spring/applicationContext-*.xml
    </param-value>
</context-param>
<listener>
	<listener-class>         org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>
   2. Servlet參數:比如前端控制器的inti-param標籤中
<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring/springmvc.xml</param-value>
		</init-param>
	</servlet>

第一種參數在Servlet中可以通過getServletContext().getInitParameter("")得到。

第二種參數只能在servlet的init()方法中通過this.getInitParameter("")取得。

3.ContextLoaderListener的源碼分析

​ 前面簡單的說明了ContextLoaderListener的作用:可以獲得ServletContext的對象和Context-param的值。接下來詳細說明下這個。

​ 首先,我們從web.xml中開始,在web.xml中我們首先配置的是contextLoaderListener,它的作用就是啓動web容器時,自動裝配ApplicationContext的配置信息。因爲它實現了ServletContextListener這個接口,在web.xml配置這個監聽器,啓動容器時,就會自動執行它實現的contextInitialized()方法。這樣就能夠在客戶端請求之前向ServletContext中添加任意的對象。

​ 在ServletContextListener中的核心邏輯便是初始化WebApplicationContext實例並存放至ServletContext中。


public void contextInitialized(ServletContextEvent event) {
		this.contextLoader = createContextLoader();
		if (this.contextLoader == null) {
			this.contextLoader = this;
		}
		this.contextLoader.initWebApplicationContext(event.getServletContext());
}

​ 通過源碼可以看出contextInitialized()中創建了一個contextLoader對象,然後該對象調用了initWebApplicationContext()。

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) {
				configureAndRefreshWebApplicationContext((ConfigurableWebApplicationContext)this.context, servletContext);
			}
			servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, 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;
		}
	}

initWebApplicationContext()主要是WebApplicationContext創建的過程:首先,驗證WebApplicationContext的存在性,通過查看ServletContext實例中是否有對應key的屬性驗證WebApplicationContext是否已經創建過實例。如果沒有通過**createWebApplicationContext()**方法來創建實例,並存放至ServletContext中。

	protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
        //
		Class<?> contextClass = determineContextClass(sc);
		if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
			throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
					"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
		}
		ConfigurableWebApplicationContext wac =
				(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
		return wac;
	}

​ 從源碼中可以詳細的看到return wac,是通過BeanUtils.instantiateClass()來創建實例,但是其中傳遞了一個contextClass,該對象是通過determineContextClass方法創建的,接下來分析該方法的源碼:

	protected Class<?> determineContextClass(ServletContext servletContext) {
        //首先從servletContext對象中獲取值
		String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
		if (contextClassName != null) {
			try {
        //該值不爲null通過forName()來裝載該類
				return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
			}
			catch (ClassNotFoundException ex) {
				throw new ApplicationContextException(
						"Failed to load custom context class [" + contextClassName + "]", ex);
			}
		}
		else {
        //servletContext中沒有該對象時
			contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
			try {
				return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
			}
			catch (ClassNotFoundException ex) {
				throw new ApplicationContextException(
						"Failed to load default context class [" + contextClassName + "]", ex);
			}
		}
	}

​ 該方法很詳細的解釋了是如何獲取CONTEXT_CLASS_PARAM(類名參數)。

首先如果contextClassName不爲空時就通過forName來裝載這個類,很明顯第一次啓動web容器時contextClassName爲空。

contextClassName爲空時通過defaultStrategies.getProperty()獲得實現類的名稱,而defaultStrategies是在ContextLoader類的靜態代碼塊中賦值的。具體的途徑,則是讀取ContextLoader類的同目錄下的ContextLoader.properties屬性文件來確定的。

org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext

​ 找到該文件後發現裏面存儲了一個鍵值對,故會加載這個類org.springframework.web.context.support.XmlWebApplicationContext

​ 也就是說,在初始化的過程中,程序會首先讀取ContextLoader類的同目錄下的屬性文件ContextLoader.properties,並根據其中的配置提取將要實現WebApplicationContext接口的實現類,並根據這個類通過反射進行實例的創建。

綜合以上的代碼:ContextLoaderListener監聽器的作用就是啓動Web容器時,自動裝配ApplicationContext的配置信息。因爲它實現了ServletContextListener這個接口,在web.xml配置了這個監聽器,啓動容器時,就會默認執行它實現的contextInitialized()方法初始化WebApplicationContext實例(XmlWebApplicationContext),並放入到ServletContext中。由於在ContextLoaderListener中關聯了ContextLoader這個類,所以整個加載配置過程由ContextLoader來完成。

​ 如果在web.xml中不寫任何參數配置信息,默認的路徑是**/WEB-INF/applicationContext.xml**,在WEB-INF目錄下創建的xml文件的名稱必須是applicationContext.xml

​ 如果是要自定義文件名可以在web.xml里加入contextConfigLocation這個context參數:

<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>
        classpath:spring/applicationContext-*.xml
    </param-value>
</context-param>

4.Servlet的初始化

​ 上面說到了配置ServletContext並初始化,那web.xml中的Servlet是如何初始化的呢?

  1. Servlet容器啓動,爲應用創建一個全局上下文環境:ServletContext對象
  2. 容器通過web.xml中的ContextLoaderListener監聽器來創建一個WebApplicationContext上下文環境對象(IOC容器)加載context-param中指定的配置文件信息到WebApplicationContext對象中,該對象在ServletContext中是以鍵值對的形式保存的。
  3. 容器初始化web.xml中配置的servlet,爲其初始化自己的上下文信息servletContext,並加載其設置的配置信息到該上下文中。將WebApplicationContext設置爲它的父容器。
  4. 此後的所有servlet的初始化都按照3步中方式創建,初始化自己的上下文環境,將WebApplicationContext設置爲自己的父上下文環境。

通過一張圖來了解上面的意思:

在這裏插入圖片描述

通過上面的圖很清楚的瞭解到:

  1. ServletContext是全局環境:裏面包含了其他的上下文環境對象通過鍵值對的形式保存。
  2. WebApplicationContext是所有Servlet的父環境:**也就是當Spring在執行getBean時,如果在自己的context(上下文環境)中找不到,那麼就會去父類中的context尋找。(反過來就不行!)**這也解釋了爲什麼我們可以在DispatcherServlet中獲取到由ContextLoaderListener對應的ApplicationContext中的bean。

參考:https://www.cnblogs.com/brolanda/p/4265597.html

https://blog.csdn.net/qq_38410730/article/details/79426673

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章