1. 程式人生 > >ServletConfig物件詳解

ServletConfig物件詳解

https://www.cnblogs.com/lashou/p/6068775.html

在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");