ServlertContext与类加载器获取Web应用中的资源文件

Web应用一般有两种资源文件,相对独立的用properties文件,剩余的用xml文件。下面的访问资源文件的代码需要背过,代码如下:
第一种:
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
//针对获取的url是因为ServletContext所获取的resource为tomcat编译后的在classes的各个servlet类,因此不是src下的类。获取到的文件流,用Properties这个类去接受,这个类专门接受后缀为properties的文件,内部数据结构为Map.
Properties pros = new Properties();
pors.load(in);
String url = pros.getProperty("url" );
String name= pros.getProperty("name"    );
String password= pros.getProperty("password");
第二种:
String path = this.getServletContext.getRealPath("/WEB-INF/classes/db.properties");
//返回给资源的绝对路径,这样就可以用传统就java代码了
FileInputStream in = new FileInputStream(path);
Properties pros = new Properties();
pors.load(in);
String url = pros.getProperty("url" );
String name= pros.getProperty("name"    );
String password= pros.getProperty("password");
还有就是在web项目中,如果没有使用servlet的情况下,我们如果直接是将servletContext直接传过来相对来时不妥,这是时候我们就需要用到类装载器来获取资源文件,这个时候需要弄清楚类装载器的生命周期。代码如下:
//这样能直接获取到更新后的资源文件,如果是这样是不能获取更新后的资源文件,代码如下:
//InputStream in = UserDao.class.getClassLoader().getResourceAsStream("db.properties");
String path = UserDao.class.getClassLoader().getResource("db.properties")getPath();
FileInputStream in = new FileInputStream(path); 
Properties pros = new Properties();
pors.load(in);
String url = pros.getProperty("url" );
String name= pros.getProperty("name"    );
String password= pros.getProperty("password");

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值