ServletContext與ServletConfig對象詳解


一、ServletContext對象詳解

ServletContext代表當前web應用

當服務器啟動,web應用加載完成后,立即創建一個ServletContext對象代表當前web應用。從此駐留在內存中唯一的代表當前web應用。直到服務器關閉或web應用移除出容器時,隨着web應用的銷毀而銷毀。

1.獲取ServletContext

servletConfig.getServletContext();
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應用的初始化:

我們可以在web.xml的根目錄下為整個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 -- 域屬性

二、ServletConfig對象詳解

在Servlet 的配置文件中,可以用一個或多個<init-param>標簽為servlet配置一些初始化參數。
當servlet配置了初始化參數之后,web容器在創建servlet實例對象時,會自動將這些初始化參數封裝到ServletConfig對象中,並在調用servlet的init方法時,將ServletConfig對象傳遞給Servlet。
進而,程序員通過Servlet對象得到當前servlet的初始化參數信息。獲取ServletConfig中初始化信息步驟:

1 . 創建私有變量:

private ServletConfig config = null;

2、重寫init方法:

 this.config = config,從而獲取ServletConfig對象;

3、獲取<init-param>配置:

//獲取初始化參數 String value1 = this.config.getInitParameter("x1");
//獲得配置文檔中<inti-param>標簽下name對應的value String value2 = this.config.getInitParameter("x2");
//獲取所有初始化參數 Enumeration e = this.config.getInitParameterNames();
while(e.hasMoreElements()){ String name = (String) e.nextElement(); String value = this.config.getInitParameter(name); System.out.println(name+"="+value); }

4、ServletConfig的作用:

獲取字符集編碼:String charset = this.config.getInitParameter("charset");
獲得數據庫連接信息:String url = this.config.getInitParameter("url");
String username = this.config.getInitParameter("username");
String password = this.config.getInitParameter("password");
獲得配置文件:String configFile = this.config.getInitParameter("config");


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM