一、ServletContext對象詳解
ServletContext代表當前web應用
當服務器啟動,web應用加載完成后,立即創建一個ServletContext對象代表當前web應用。從此駐留在內存中唯一的代表當前web應用。直到服務器關閉或web應用移除出容器時,隨着web應用的銷毀而銷毀。
1.獲取ServletContext
this.getServletContext();
在web.xml中的<web-app>根標簽下定義<context-param>,可以給全局定義初始化參數,比如encode
在servlet中調用時,this.getServletContext().getInitParamter("encode"),得到String型的變量
2.加載資源文件:
路徑難題
ServletContext.getRealPath("xxxxx");//會在傳入的路徑前拼接上當前web應用的硬盤路徑。~另外在沒有ServletContext的環境下,我們可以使用類加載器加載資源。但是要注意,類加載器加載資源時,路徑要相對於平常加載類的位置進行計算。
ClassLoader.getResource().getPath();
ClassLoader.getResourceAsStream();
3.讀取web應用的初始化:
在<Context-param>標簽下添加
可以通過ServletContext對象來讀取這些整個web應用的初始化參數。
servletContext.getInitParamter();
servletContext.getInitParamterNames();
4.作為域對象使用:
域:一個對象具有了一個可以被看見的范圍,那么利用這個對象身上的Map,可以在這個范圍內共享數據,這樣的對象叫做域對象。
javaweb中一共有四大作用域,其中ServletContext就是其中最大的一個。setAttribute(String name,Object value);
getAttribute(String name);
removeAttribute(String name);
getAttributeNames();
5.ServletContext域的范圍:
在整個web應用中共享數據
生命周期:
服務器啟動web應用加載ServletContext創建,直到服務器關閉或web應用移除出容器時隨着web應用的銷毀,ServletContext銷毀。
主要的作用:
在整個web應用中共享數據。paramter -- 請求參數
initparamter -- 初始化參數
attribute -- 域屬性