問題:
不同的使用者使用相同的資料
解決:
ServletContext對象
特點:
伺服器建立
使用者共享
作用域:
整個項目内
生命周期:
伺服器啟動到伺服器關閉
使用:
擷取ServletContext對象
//第一種方式
ServletContext sc=this.getServletContext();
//第二種方式
ServletContext sc2=this.getServletConfig().getServletContext();
//第三種方式
ServletContext sc3=req.getSession().getServletContext();
使用ServletContext對象完成資料共享
//資料存儲
sc.setAttribute(String name, Object value);
//資料擷取
sc.getAttribute("str"); 傳回的是Object類型
注意:
不同的使用者可以給ServletContext對象進行資料的存取
擷取的資料不存在時傳回null
擷取項目中的web.xml檔案中的全局配置資料
sc.getInitParameter(String name); 根據鍵的名字傳回web.xml中配置的全局資料的值,傳回String類型
如果資料不存在傳回null
sc.getInitParameterNames();傳回鍵名的枚舉
配置方式:注意一組<context-param>标簽隻能存儲一組鍵值對資料,多組可以聲明多個<context-param>進行存儲
<context-param>
<param-name>name</param-name>
<param-value>zhangsan</param-value>
</context-param>
全局配置資料的作用:
将靜态資料和代碼進行解耦
擷取項目Webroot下的資源的絕對路徑
String path=sc.getRealPath(String path);
示例:String path=sc.getRealPath("/doc/1.txt");
擷取的路徑為項目根目錄,path參數為項目根目錄中的路徑
擷取Webroot下的資源的流對象
InputStream is=sc.getResourceAsStream(String path);
path參數為項目根目錄中的路徑
示例:InputStream is=sc.getResourceAsStream("/doc/1.txt");
注意:
此種方式隻能擷取項目根目錄下的資源流對象,Class檔案的流對象需要使用類加載器擷取。