Sami
Sami

Reputation: 2331

How to add two properties files to JSF

I have two properties files, but something is wrong, inputStream is always 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? If not, how can I read from my bundle only those properties which key has a prefix key_?

Thanks Sami

Upvotes: 2

Views: 1819

Answers (1)

BalusC
BalusC

Reputation: 1108782

You forgot to include the resources package in the path. 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 bundle = ResourceBundle.getBundle("resources.avainsanat", FacesContext.getCurrentInstance().getViewRoot().getLocale());
// ...

(note that you should actually have used a <base-name>resources.avainsanat</base-name>)

Alternatively, if the bean is request scoped, you could also just inject #{avainsanat} as managed property:

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

Or to programmatically evaluate it:

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

Upvotes: 5

Related Questions