ServletContext学习笔记---------从今天开始养成写笔记总结的好习惯!

  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);




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值