一般來說,對于整個應(yīng)用的配置,為了不使用"硬編碼",應(yīng)該使用ServletContext對象。
而如果只有一個特定的Servlet需要設(shè)定的參數(shù),其他Servlet不能訪問,那么一般要使用ServletConfig();
PS:在使用ServletConfig對象的時候,在init()方法中,一定要用super類初始化ServletConfig對象。








下面來逐個討論:
一, ServletContext對象
<context-param>元素:設(shè)定Context起始參數(shù)
在web.xml中,您可以利用<context-param>元素來定義Context起始參數(shù),它包含兩個子元素:
n <param-name>:定義Context起始參數(shù)名稱
n <param-value>:定義Context起始參數(shù)值
以下是<context-param>元素的使用范例,在本例中筆者定義了兩個Context起始參數(shù):
n driver_type:Web應(yīng)用程序欲使用的JDBC驅(qū)動程序名稱
n url:目標(biāo)數(shù)據(jù)庫位置





















有兩種方式存取Context起始參數(shù)的方式:
表1 在ServletContext接口中用來存取Context起始參數(shù)的方法
方法名稱 |
回傳類型 |
用 途 |
getInitParameter() |
String |
取得某個Context起始參數(shù)值 |
getInitParameterNames() |
java.util.Enumeration |
取得所有Context起始參數(shù) |
1.先調(diào)用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. 直接調(diào)用getServletContext()方法取得ServletContext對象。
ServletContext context = getServletContext();
//獲得配置的參數(shù)
String driver_type = context.getInitParameter("drvier_type");
String url=context.getInitParameter("url");
//獲得當(dāng)前WebApp的路徑
String path=context.getRealPath("/");
二, ServletConfig對象
<init-param>元素:設(shè)定init起始參數(shù)
在web.xml中,您可以利用<init-param>元素來定義Config起始參數(shù),它包含兩個子元素:
n <init-name>:定義Config起始參數(shù)名稱
n <init-value>:定義Config起始參數(shù)值
以下是<init-param>元素的使用范例,在本例中筆者定義了兩個Config起始參數(shù):
n driver_type:Web應(yīng)用程序欲使用的JDBC驅(qū)動程序名稱
n url:目標(biāo)數(shù)據(jù)庫位置










<init-param>










在init()方法中,應(yīng)該:










