ServletContext用于读取资源文件
代码模板
InputStream in = this.getServletcontext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties props = new Properties();//这个对象其实是用web来内部存储
props.load(in);
String url = props.getProperty("url");
String url = props.getProperty("username");
String url = props.getProperty("password");
还有一种传统方式可以用来读取资源文件//这样做的好处是可以得到资源的名称
String path = this.getServletcontext()..getRealPath();
String filename = path.substring(path.getlastIndexof("\\")+1);
system.print.out(filename);//这里输出db.properties
FileInputStream fin = new FileInputStream(path);//一定要注意这里必须是绝对路径,相对路径是行不通的
Properties props = new Properties();//这个对象其实是用web来内部存储
props.load(in);
String url = props.getProperty("url");
String url = props.getProperty("username");
String url = props.getProperty("password");
如果不在servlet里读取资源文件(比如在DAO层),我们一般通过类装载器来读取//这种方式有两个问题,一是资源文件不宜太大,二是无法获取更新后的数据
public class UserDao{
private static Properties props= new Properties();
static{
try{
InputStream in = UserDao.class.getClassLoader().getResourceAsStream("db.properties");
props.load(in);
}catch(Exception e){
throw new ExceptionInintError(e);//这是一个致命错误一定要传给服务器
}
}
}
//用下面的方式通过类装载器读取资源文件可以获得更新后的数据
String path = UserDao.class.getClassLoader().getResource("db.properties").getPath();
FileInputStream fin = new FileInputStream(path);
Properties props = new Properties();//这个对象其实是用web来内部存储
props.load(in);