為每一Servlet設置初始化參數
可以為每一個Servlet在對應的web.xml中的Servlet節點下編寫初始化參數,格式如下:
<init-param>
<param-name>userName</param-name>
<param-value>admin</param-value>
</init-param>
然后在servlet中用如下代碼獲取相應的參數:
ServletConfig config = this.getServletConfig();
this.username = config.getInitParameter("userName");
為所有的Servlet設置公用的初始化參數
可以為所有的Servlet設置公用初始化參數,該參數和上面的參數有所不同,上面的要放在對應的Servlet節點下,而公用參數不用也不能放在Servlet節點下。
<context-param>
<param-name>userName</param-name>
<param-value>admin</param-value>
</context-param>
同樣在Servlet中可以通過如下代碼獲取我們設置的全局配置信息對象:
ServletContext context = this.getServletContext();
String userNameInGlobal = context.getInitParameter("userName");
在代碼中設置公用屬性
可以在代碼中為ServletContext設置屬性,然后就可以在任意地方獲取了。該屬性是全局屬性,一旦設置成功后,在整個容器中均可以使用。
ServletContext context = this.getServletContext(); context.setAttribute("maxNumber", 999); int maxNumebrInContext = (int)context.getAttribute("maxNumber");
|
讀取外部文件中的配置信息
通過ServletContext對象讀取外部文件中的配置信息主要有三種形式:
- getResource
- 返回一個URL對象,然后調用openStream()方法獲取InputStream
- getResourceAsStream
- 直接返回InputStream對象
- getRealPath
- 返回資源文件的絕對路徑,然后通過絕對路徑用FileInputStream類讀取數據
在classes目錄下有一個Person.properties文件,內容如下:
getResource獲取外部文件
@Override public void init() throws ServletException { ServletContext ctx = this.getServletContext(); String resourcePath = "/WEB-INF/classes/Person.properties"; try { URL url = ctx.getResource(resourcePath); InputStream is = url.openStream(); String name = getPropertiesByKey("name", is); System.out.println(name); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
//從Stream中讀取properties信息 public static String getPropertiesByKey(String key, InputStream is) { Properties properties = new Properties(); try { properties.load(is); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
String value = (String) properties.get(key); return value; }
|
getResourceAsStream獲取外部文件
public void init() throws ServletException { ServletContext ctx = this.getServletContext(); String resourcePath = "/WEB-INF/classes/Person.properties"; InputStream is = ctx.getResourceAsStream(resourcePath); String age = getPropertiesByKey("age", is); System.out.println("年齡是: "+ age); } |
getRealPath獲取外部文件
public void init() throws ServletException { ServletContext ctx = this.getServletContext(); String resourcePath = "/WEB-INF/classes/Person.properties"; String resourceRealPath = ctx.getRealPath(resourcePath); try { InputStream is = new FileInputStream(new File(resourceRealPath)); String address = getPropertiesByKey("address", is); System.out.println("地址是:" + address); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }
} |