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