以JSF Web应用程序的静态代码读取.properties文件 [英] read .properties file in static code of a JSF web application

查看:45
本文介绍了以JSF Web应用程序的静态代码读取.properties文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从静态块的属性文件中获取数据库连接参数.属性文件的位置为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.

  1. 将其作为/WEB-INF/db.properties直接移动到/WEB-INF文件夹中,并按以下方式加载:

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

(请注意缺少/前缀)

另请参见:

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