如何访问java类中WEB-INF文件夹下的文件 [英] How to access a file under WEB-INF folder in java class

查看:221
本文介绍了如何访问java类中WEB-INF文件夹下的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Web应用程序中有一个普通的java类,想要读取 WEB-INF 文件夹下的配置文件。我知道如果它在类路径( WEB-INF / classes 文件夹)中访问该文件的方式。由于 WEB-INF / classes 文件夹用于 .class 文件,我想将我的配置文件保存在 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.

谁能告诉我如何从我的java类访问它?

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

推荐答案

ServletContext .getResourceAsStream()将从相对于WAR文件根目录的给定路径加载文件。类似于:

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

这里的主要问题是你需要访问servlet上下文才能做到这一点。您可以在servlet或过滤器中使用它,但不能在应用程序中的非Web组件中使用它。您有几个选择:

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:


  • 通过应用程序范围的变量使servlet上下文从Web层可用到服务层,或者注入或其他方式

  • 将资源加载代码放入Web层,并将其公开给服务层

  • 加载配置Web层,并将其传递给服务层

这篇关于如何访问java类中WEB-INF文件夹下的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆