一般來說,對于整個應用的配置,為了不使用"硬編碼",應該使用ServletContext對象。
而如果只有一個特定的Servlet需要設定的參數,其他Servlet不能訪問,那么一般要使用ServletConfig();
PS: 在使用ServletConfig對象的時候,在init()方法中,一定要用super類初始化ServletConfig對象。
1
2
3
4
5
6
|
public void init(ServletConfig config) throws ServletException { super .init(config); //TODO } |
下面來逐個討論:
一、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:目標數據庫位置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<web-app> <context-param> <param-name>driver_type</param-name> <param-value>oracle.jdbc.driver.OracleDriver</param-value> </context-param> <context-param> <param-name>url</param-name> <param-value>jdbc:oracle:thin: @IP : 1521 :SID</param-value> </context-param> </web-app> |
有兩種方式存取Context起始參數的方式:
表1 在ServletContext接口中用來存取Context起始參數的方法
方法名稱 |
回傳類型 |
用 途 |
getInitParameter() |
String |
取得某個Context起始參數值 |
getInitParameterNames() |
java.util.Enumeration |
取得所有Context起始參數 |
1. 先調用getServletConfig()方法取得ServletConfig對象,再利用ServletConfig接口定義的getServletContext()方法取得ServletContext對象。
1
2
|
ServletConfig config = getServletConfig(); ServletContext context = config.getServletContext(); |
1
2
|
String driver_type = context.getInitParameter("drvier_type"); String url=context.getInitParameter("url"); |
2. 直接調用getServletContext()方法取得ServletContext對象。
1
2
3
4
5
6
7
|
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起始參數:
n driver_type:Web應用程序欲使用的JDBC驅動程序名稱
n url:目標數據庫位置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<web-app> <servlet> <servlet-name>testServlet</servlet-name> <servlet- class >com.simon.test.servlet.initparam.testServlet</servlet- class > <init-param> <param-name>driver_type</param-name> <param-value>oracle.jdbc.driver.OracleDriver</param-value> </init-param> <init-param> <param-name>url</param-name> <param-value>jdbc:oracle:thin: @IP : 1521 :SID</param-value> </init-param> <servlet-mapping> <servlet-name>testServlet</servlet-name> <url-pattern>/testServlet</url-pattern> </servlet-mapping> </web-app> |
在init()方法中,應該:
1
2
3
4
5
6
7
8
9
|
public void init(ServletConfig config) throws ServletException { //必須要繼承super類的init()方法 super .init(config); String filename=getServletConfig().getInitParameter( "config-file" ); //TODO } |
以上這篇有關ServletConfig與ServletContext的訪問就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。