从XHTML文件中的属性文件中获取值

时间:2016-08-24 11:12:35

标签: jsf

我的本​​地文件系统中有一个属性文件。 我使用XHTML文件来创建UI。 在这个文件中,我已经硬编码了UI元素的名称。有没有办法从属性文件中获取这些名称?

1 个答案:

答案 0 :(得分:0)

有几个选项,假设您在以下位置有一个messages.properties

src
   main
      java
      resources 
         com
            example
               messages.properties

您可以使用resource-bundle中的faces-config.xml标记来扩展应用

<application>
   <locale-config>
        <default-locale>en</default-locale>
        <supported-locale>fr</supported-locale>
    </locale-config>
   <resource-bundle>
      <baseName>com.example.messages</baseName>
      <var>msgs</var>
   </resource-bundle>
</application>

然后可以在您的XHTML中访问它(请注意,使用locale可以选择使用messages_fr.properties)

<f:view locale="en">
   #{msgs.keyName}
</f:view>
<f:view locale="fr">
   #{msgs.keyName}
</f:view>

您也可以使用<f:loadBundle>

<f:view locale="en">
   <f:loadBundle baseName="com.example.messages" var="msgs" />
   #{msgs.keyName}
</f:view>
<f:view locale="fr">
   <f:loadBundle baseName="com.example.messages" var="msgs" />
   #{msgs.keyName}
</f:view>

如果您需要资源包是外部的,则可能采用以下方法。

在web.xml中设置捆绑包的绝对路径

<context-param>
    <param-name>bundlePath</param-name>
    <param-value>absolute path to your properties file</param-value>
</context-param>

创建自己的ResourceBundle类

package com.example;

import java.io.FileReader;

import java.util.Enumeration;
import java.util.ResourceBundle;
import java.util.PropertyResourceBundle;

import javax.faces.context.FacesContext;

public class MyBundle extends ResourceBundle {

    public MyBundle() throws FileNotFoundException {
        String configPath = FacesContext.getCurrentInstance().getExternalContext().getInitParameter("bundlePath")
        setParent(new PropertyResourceBundle(new FileReader(configPath)));
    }

    @Override
    public Object handleGetObject(String key) {
        return parent.getObject(key);
    }

    @Override
    public Enumeration<String> getKeys() {
        return parent.getKeys();
    }

}

按照惯例<{1}}注册

faces-config.xml