以JSF Web应用程序的静态代码读取.properties文件 [英] read .properties file in static code of a JSF web application
问题描述
我想从静态块的属性文件中获取数据库连接参数.属性文件的位置为WEB-INF/classes/db.properties
.
I would like to get DB connection parameters from a properties file in a static block. The properties file location is WEB-INF/classes/db.properties
.
我将更喜欢使用getResourceAsStream()
方法.我尝试了很多方法,但是它们都返回了null
.
I will prefer to use getResourceAsStream()
method. I have tried many ways, but they all returned null
.
private static Properties prop = new Properties();
static{
try {
FacesContext facesContext = FacesContext.getCurrentInstance();
ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
InputStream inputStream = servletContext.getResourceAsStream("/db.properties");
InputStream is = prop.getClass().getResourceAsStream("/db.properties");
if(inputStream!=null){//it is null
prop.load(inputStream);
}
if(is!=null){//it is null
prop.load(is);
}
} catch (Exception e) {
e.printStackTrace();
}
}
这是怎么引起的,我该如何解决?
How is this caused and how can I solve it?
推荐答案
InputStream inputStream = servletContext.getResourceAsStream("/db.properties");
此尝试期望文件位于/WebContent/db.properties
中.
This attempt expects the file to be in /WebContent/db.properties
.
InputStream is = prop.getClass().getResourceAsStream("/db.properties");
此尝试希望它至少与java.util.Properties
类位于同一存档(JAR)中.
This attempt expects it to be in at least the same archive (JAR) as the java.util.Properties
class.
这些尝试均不会读取您放置在/WEB-INF/classes/db.properties
中的文件.您基本上可以通过两种方法解决此问题.
Neither of those attempts reads the file which you've placed in /WEB-INF/classes/db.properties
. You can fix this problem in basically 2 ways.
-
将其作为
/WEB-INF/db.properties
直接移动到/WEB-INF
文件夹中,并按以下方式加载:
Move it directly in the
/WEB-INF
folder as/WEB-INF/db.properties
and load it as follows:
InputStream input = externalContext.getResourceAsStream("/WEB-INF/db.properties");
(请注意,您无需从JSF的幕后拖拉ServletContext
;为此已经有一个委托方法)
(note that you don't need to haul the ServletContext
from under the JSF's hoods; there's already a delegate method for that)
相对于/WEB-INF/classes
中也存在的类加载它,例如当前的托管bean类.
Load it relative to the class which is also present in /WEB-INF/classes
, e.g. the current managed bean class.
InputStream input = Bean.class.getResourceAsStream("/db.properties");
或者仅使用上下文类加载器,它就可以访问所有内容.
Or just use the context classloader, it has access to everything.
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
(请注意缺少/
前缀)
另请参见:
- 其中在基于servlet的应用程序中放置以及如何读取配置资源文件?
- Where to place and how to read configuration resource files in servlet based application?
See also:
这篇关于以JSF Web应用程序的静态代码读取.properties文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!