JSP-->web應(yīng)用中屬性文件使用 (轉(zhuǎn)載)
Posted on 2007-09-27 21:41 瘋狂 閱讀(525) 評論(0) 編輯 收藏
在web應(yīng)用中,一些數(shù)據(jù)庫連接參數(shù)或者系統(tǒng)本身的參數(shù)通常不是寫在程序中的,需要保存成屬性文件的形式或者XML文件的形式。二者各有優(yōu)缺點,屬性文件的形式操作和管理比較簡單,XML文件形式則能提供很強大,并且層次性很好的屬性文件的配置。
下面講解在web應(yīng)用中通過屬性文件的方式來記錄一些重要的參數(shù)。
下面的例子以一個數(shù)據(jù)庫連接參數(shù)為例子,開發(fā)環(huán)境是Eclipse,部署環(huán)境是Tomcat。
屬性文件內(nèi)容如下所示:
init.properties
-------------------------------------------------------------
drivers=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:test
username=testuser
password=test
-------------------------------------------------------------
訪問該屬性文件的代碼:
InitPropertiesLoader.java
-------------------------------------------------------------------
package com.knight.commons
public class InitPropertiesLoader
{
/**
* 直接讀取classpath中的屬性文件
* @param filename 文件名稱和路徑
* @return
*/
public Properties getProperties(String filename)
{
Properties prop = new Properties();
InputStream in = null;
try
{
in = getClass().getResourceAsStream(filename);
prop.load(in);
}
catch (Exception e)
{
log.info("無法正確讀取數(shù)據(jù)庫連接配置屬性文件!");
}
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch (Exception e)
{
}
}
return prop;
}
}
-------------------------------------------------------------------
ConnectionManager.java
-------------------------------------------------------------------
package com.knight.commons.database
public class ConnectionManager
{
private static String driverName = null;
private static String url = null;
private static String username = null;
private static String password = null;
private static Properties prop = null;
public void init()
{
try
{
prop = new InitPropertiesLoader().getProperties("/init.properties");
driverName = prop.getProperty("drivers");
url = prop.getProperty("url");
username = prop.getProperty("username");
password = prop.getProperty("password");
}
catch (Exception e)
{
log.info("讀取屬性配置文件時出錯!");
}
finally
{
try
{
if (prop != null)
prop.clear();
}
catch (Exception e)
{
log.info(e.getMessage());
}
}
}
public static Connection getConnection()
{
Connection conn = null;
//初始化數(shù)據(jù)庫連接參數(shù)
init();
try
{
Class.forName(driverName);
conn = DriverManager.getConnection(url, username, password);
}
catch (Exception e)
{
log.info("There is some error when you get a connection.");
log.info(e.getMessage());
}
return conn;
}
}
-------------------------------------------------------------------
上面就是涉及到的幾個主要文件,為了既能在IDE環(huán)境中使用該屬性配置文件,又能在實際的web應(yīng)用中保證該屬性文件的正常調(diào)用。該屬性文件存放的位置很重要。
"/init.properties"表示該屬性文件存放在CLASSPATH的跟目錄中,在Eclipse環(huán)境下存放在工程/bin下。
在web應(yīng)用中init.properties存放在當前應(yīng)用的WEB-INF/classes目錄下。更簡單的處理方式是將init.properties打到工程的包中。這樣,當多個應(yīng)用部署在同一個Context下時,相互之間能夠保持獨立性。但是這時候千萬要注意同一個Context下多個應(yīng)用的屬性文件是否文件命名沖突。
附打包后目錄的層次:
/
init.properties
/com/knight/commons
InitPropertiesLoader.class
/com/knight/commons/database
ConnectionManager.class