java类中如何访问WEB-INF文件夹下的文件 [英] How to access a file under WEB-INF folder in java class
问题描述
我在 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屋!