<context-param>的作用:
web.xml的配置中<context-param>配置作用
1. 啟動一個WEB項目的時候,容器(如:Tomcat)會去讀它的配置檔案web.xml.讀兩個節點:
<listener></listener> 和 <context-param></context-param>
2.緊接着,容器建立一個ServletContext(上下文),這個WEB項目所有部分都将共享這個上下文.
3.容器将<context-param></context-param>轉化為鍵值對,并交給ServletContext.
4.容器建立<listener></listener>中的類執行個體,即建立監聽.
5.在監聽中會有contextInitialized(ServletContextEvent
args)初始化方法,在這個方法中獲得ServletContext = ServletContextEvent.getServletContext();
context-param的值 = ServletContext.getInitParameter("context-param的鍵");
6.得到這個context-param的值之後,你就可以做一些操作了.注意,這個時候你的WEB項目還沒有完全啟動完成.這個動作會比所有的Servlet都要早.
換句話說,這個時候,你對<context-param>中的鍵值做的操作,将在你的WEB項目完全啟動之前被執行.
7.舉例.你可能想在項目啟動之前就打開資料庫.
那麼這裡就可以在<context-param>中設定資料庫的連接配接方式,在監聽類中初始化資料庫的連接配接.
8.這個監聽是自己寫的一個類,除了初始化方法,它還有銷毀方法.用于關閉應用前釋放資源.比如說資料庫連接配接的關閉.
如:
<!-- 加載spring的配置檔案 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml,/WEB-INF/action-servlet.xml,/WEB-
INF/jason-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>