实际开发中一般不会将连接数据库的操作使用Servlet,因为我们为了分层,而是将连接数据库的操作放到dao中,这样就会用到普通的Java类来读取配置文件(.properties的文件),那么普通的Java如何来读取配置文件呢?
请看下面实例:
文件1:db.properties配置文件
userName=shxt
password=shxt
url=jdbc\:oracle\:thin\:@localhost\:1521\:ORCL
driver=oracle.jdbc.driver.OracleDriver
文件2:ch11JavaReadProperties.java 普通java文件
packagecn.com.shxt.ch10;
importjava.io.InputStream;
importjava.util.Properties;
publicclassch11JavaReadProperties {
privatestaticPropertiesdbconfig=newProperties();
privateStringurl=null;
privateStringusername=null;
privateStringpassword=null;
static{
try{
InputStreamin = ch11JavaReadProperties.class.getClassLoader()
.getResourceAsStream("db.properties");
dbconfig.load(in);
}catch(Exception e) {
e.printStackTrace();
}
}
/**
* 获取配置文件db.properties中连接数据库的参数
*/
publicvoidgetParameter() {
url=dbconfig.getProperty("url");
username=dbconfig.getProperty("userName");
password=dbconfig.getProperty("password");
System.out.println(" url:"+url+" 用户名:"+username+" 密码:"+password);
}
/**
*主测试方法
*/
publicstaticvoidmain(String[] args) {
ch11JavaReadProperties jdbc =newch11JavaReadProperties();
jdbc.getParameter();
}
}
我们只要在Servlet中实例化ch11JavaReadProperties并调用getParameter()方法就可以获取到db.properties中连接数据库的参数了。请注意:使用类装载器读取配置文件时,配置文件不宜太大,因为类装载器将配置文件装载到内存,若配置文件过大(比如1G),容易导致内存溢出的问题。
通过类装载器读取配置文件具有致命的缺点:如果服务器不重启,即使你更改了配置文件的内容,Java程序读取到的配置参数还是原来第一次配置的参数,由于程序从内存中读取配置文件的参数,因为内存中已经存在了,即使你更改了配置文件参数,内存却不会自动更新。
如果我们更改了配置文件,不用重新启动服务器就要求程序自动读取到更新后的配置文件,该怎么办呢??
请见下面程序:ch11_2JavaReadProperties .java
package cn.com.shxt.ch10;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
public class ch11_2JavaReadProperties {
private static Properties dbconfig = new Properties();
private String url=null;
private String username=null;
private String password=null;
/**
* 获取配置文件db.properties中连接数据库的参数
*/
public void getParameter() {
try {
String path = ch11_2JavaReadProperties.class.getClassLoader()
.getResource("db.properties").getPath();
FileInputStream in=new FileInputStream(path);
dbconfig.load(in);
} catch (Exception e) {
e.printStackTrace();
}
url = dbconfig.getProperty("url");
username = dbconfig.getProperty("userName");
password = dbconfig.getProperty("password");
System.out.println(" url:" + url + " 用户名:" + username + "密码:"+ password);
}
/**
*主测试方法
*/
public static void main(String[] args) {
ch11_2JavaReadProperties jdbc = new ch11_2JavaReadProperties();
jdbc.getParameter();
}
}
本类的ch11_2JavaReadProperties.class.getClassLoader().getResource("db.properties").getPath()是把资源当做URL返回,得到资源的路径,不是再通过类装载器来读,而是通过传统的方式来读,我们通过类装载的方式来读取文件的位置,得到位置后再通过传统的读取方式来读,这样就可以避免重启服务器而可以读取到更新后的数据。