【问题标题】:read .properties file in static code of a JSF web application在 JSF Web 应用程序的静态代码中读取 .properties 文件
【发布时间】:2012-04-01 09:35:32
【问题描述】:

我想从静态块中的属性文件中获取数据库连接参数。属性文件位置是WEB-INF/classes/db.properties

我更喜欢使用getResourceAsStream() 方法。我尝试了很多方法,但都返回了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();
    }
}

这是怎么引起的,我该如何解决?

【问题讨论】:

标签: jsf properties


【解决方案1】:

正如 Thufir 在评论中所写,有一个很好的从 Java 代码读取属性的教程:http://jaitechwriteups.blogspot.ca/2007/01/how-to-read-properties-file-in-web.html

/** 
 * Some Method 
 *  
 * @throws IOException 
 *  
 */  
public void doSomeOperation() throws IOException {  
    // Get the inputStream  
    InputStream inputStream = this.getClass().getClassLoader()  
            .getResourceAsStream("myApp.properties");  

    Properties properties = new Properties();  

    System.out.println("InputStream is: " + inputStream);  

    // load the inputStream using the Properties  
    properties.load(inputStream);  
    // get the value of the property  
    String propValue = properties.getProperty("abc");  

    System.out.println("Property value is: " + propValue);  
}  

【讨论】:

  • 这并不能完全回答/解释 OP 的具体问题/问题。
【解决方案2】:
InputStream inputStream = servletContext.getResourceAsStream("/db.properties"); 

此尝试要求文件位于/WebContent/db.properties

InputStream is = prop.getClass().getResourceAsStream("/db.properties");

此尝试期望它至少与java.util.Properties 类位于相同的存档 (JAR) 中。

这些尝试都不会读取您放在/WEB-INF/classes/db.properties 中的文件。您可以通过两种方式解决此问题。

  1. /WEB-INF文件夹中直接移动为/WEB-INF/db.properties并加载如下:

    InputStream input = externalContext.getResourceAsStream("/WEB-INF/db.properties");
    

    (请注意,您不需要从 JSF 的底层获取 ServletContext;已经有一个委托方法)

  2. 相对于 /WEB-INF/classes 中也存在的类加载它,例如当前托管的 bean 类。

    InputStream input = Bean.class.getResourceAsStream("/db.properties");
    

    或者只使用上下文类加载器,它可以访问所有内容。

    InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
    

    (注意缺少/ 前缀)

另见:

【讨论】:

    猜你喜欢
    • 2011-05-17
    • 1970-01-01
    • 2013-12-13
    • 2020-04-08
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    相关资源
    最近更新 更多