格式定義:
<context-param> <param-name>contextconfiglocation</param-name> <param-value>contextconfiglocationvalue></param-value> </context-param>
作用:該元素用來聲明應用範圍(整個web項目)内的上下文初始化參數。 param-name 設定上下文的參數名稱。必須是唯一名稱 param-value 設定的參數名稱的值
初始化過程:
在啟動web項目時,容器(比如tomcat)會讀web.xml配置檔案中的兩個節點<listener>和<contex-param>。
接着容器會建立一個servletcontext(上下文),應用範圍内即整個web項目都能使用這個上下文。
接着容器會将讀取到<context-param>轉化為鍵值對,并交給servletcontext。
容器建立<listener></listener>中的類執行個體,即建立監聽(備注:listener定義的類可以是自定義的類但必須需要繼承servletcontextlistener)。
在監聽的類中會有一個contextinitialized(servletcontextevent event)初始化方法,在這個方法中可以通過event.getservletcontext().getinitparameter("contextconfiglocation") 來得到context-param 設定的值。在這個類中還必須有一個contextdestroyed(servletcontextevent event) 銷毀方法.用于關閉應用前釋放資源,比如說資料庫連接配接的關閉。
得到這個context-param的值之後,你就可以做一些操作了.注意,這個時候你的web項目還沒有完全啟動完成.這個動作會比所有的servlet都要早。
由上面的初始化過程可知容器對于web.xml的加載過程是context-param >> listener >> fileter >> servlet
如何使用
頁面中
${initparam.contextconfiglocation}
servlet中
string paramvalue=getservletcontext().getinitparameter("contextconfiglocation")
原文連結:
<a href="http://blog.csdn.net/liaoxiaohua1981/article/details/6759206" target="_blank">http://blog.csdn.net/liaoxiaohua1981/article/details/6759206</a>