java中的inf,如何访问java类中WEB-INF文件夹下的文件

I have a plain java class in a web application and want to read a configuration file under WEB-INF folder. I know the way to access the file if its in the classpath (WEB-INF/classes folder). Since WEB-INF/classes folder is meant for .class files, I want to keep my configuration file under WEB-INF folder only.

Can anyone tell me how I can access it from my java class?

解决方案

ServletContext.getResourceAsStream() will load a file from a given path relative to the root of the WAR file. Something like:

ServletContext ctx;

InputStream configStream = ctx.getResourceAsStream("/WEB-INF/config.properties");

The major issue here is that you need access to the servlet context to be able to do this. You have that in a servlet or a filter, but not in a non-web component further back in the application. You have a few options:

Make the servlet context available from the web layer to the service layer, via an application-scoped variable, or injection, or some other way

Put the resource-loading code in the web layer, and expose that to the service layer

Load the configuration in the web layer, and pass it on to the service layer

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值