一般來說,對于整個應用的配置,為了不使用"硬編碼",應該使用ServletContext對象。 而如果只有一個特定的Servlet需要設定的參數,其他Servlet不能訪問,那么一般要使用ServletConfig(); PS:在使用ServletConfig對象的時候,在init()方法中,一定要用super類初始化ServletConfig對象。
下面來逐個討論: 一, ServletContext對象 <context-param>元素:設定Context起始參數 在web.xml中,您可以利用<context-param>元素來定義Context起始參數,它包含兩個子元素:
n <param-name>:定義Context起始參數名稱
n <param-value>:定義Context起始參數值
以下是<context-param>元素的使用范例,在本例中筆者定義了兩個Context起始參數:
n driver_type:Web應用程序欲使用的JDBC驅動程序名稱
n url:目標數據庫位置
有兩種方式存取Context起始參數的方式: 表1 在ServletContext接口中用來存取Context起始參數的方法
方法名稱
回傳類型
用 途
getInitParameter()
String
取得某個Context起始參數值
getInitParameterNames()
java.util.Enumeration
取得所有Context起始參數
1.先調用getServletConfig()方法取得ServletConfig對象,再利用ServletConfig接口定義的getServletContext()方法取得ServletContext對象。 ServletConfig config = getServletConfig(); ServletContext context = config.getServletContext(); String driver_type = context.getInitParameter("drvier_type"); String url=context.getInitParameter("url"); 2. 直接調用getServletContext()方法取得ServletContext對象。 ServletContext context = getServletContext(); //獲得配置的參數 String driver_type = context.getInitParameter("drvier_type"); String url=context.getInitParameter("url"); //獲得當前WebApp的路徑 String path=context.getRealPath("/");
二, ServletConfig對象 <init-param>元素:設定init起始參數 在web.xml中,您可以利用<init-param>元素來定義Config起始參數,它包含兩個子元素:
n <init-name>:定義Config起始參數名稱
n <init-value>:定義Config起始參數值
以下是<init-param>元素的使用范例,在本例中筆者定義了兩個Config起始參數:
在init()方法中,應該: