简体   繁体   English

如何将两个属性文件添加到JSF

[英]How to add two properties files to JSF

I have two properties files, but something is wrong, inputStream is always null? 我有两个属性文件,但是出了点问题,inputStream总是为null?

<application>
    <resource-bundle>
        <base-name>resources/Bundle</base-name>
        <var>bundle</var>
    </resource-bundle>
    <locale-config>
        <default-locale>fi</default-locale>
        <supported-locale>fi</supported-locale>

    </locale-config>

    <resource-bundle>
        <base-name>resources/avainsanat</base-name>
        <var>avainsanat</var>
    </resource-bundle>
</application>

 public static List getAvainsanat() throws IOException {
    InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("avainsanat.properties");

    Properties properties = new Properties();
    List<String> values = new ArrayList<>();
    System.out.println("InputStream is: " + input);

    for (String key : properties.stringPropertyNames()) {
        String value = properties.getProperty(key);
        values.add(value);

    }
    return values;
}

Is it even possible to have two or more properties files in faces-config? 在faces-config中甚至可能有两个或更多属性文件吗? If not, how can I read from my bundle only those properties which key has a prefix key_? 如果没有,如何从捆绑包中仅读取键具有前缀key_的那些属性?

Thanks Sami 谢谢萨米

You forgot to include the resources package in the path. 您忘记在路径中包含resources包。 The context class loader searches always relative to the classpath root. 上下文类加载器总是相对于类路径根搜索。

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("resources/avainsanat.properties");

The more correct way is in this particular case however using ResourceBundle#getBundle() , which is also exactly what JSF is using under the covers for <resource-bundle> : 在这种特殊情况下,更正确的方法是使用ResourceBundle#getBundle() ,这也是JSF在<resource-bundle>幕后使用的:

ResourceBundle bundle = ResourceBundle.getBundle("resources.avainsanat", FacesContext.getCurrentInstance().getViewRoot().getLocale());
// ...

(note that you should actually have used a <base-name>resources.avainsanat</base-name> ) (请注意,您实际上应该已经使用了<base-name>resources.avainsanat</base-name>

Alternatively, if the bean is request scoped, you could also just inject #{avainsanat} as managed property: 另外,如果bean是请求范围的,则还可以注入#{avainsanat}作为托管属性:

@ManagedProperty("#{avainsanat}")
private ResourceBundle bundle;

Or to programmatically evaluate it: 或以编程方式对其进行评估:

FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle bundle = context.getApplication().evaluateExpressionGet(context, "#{avainsanat}", ResourceBundle.class);
// ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM