从XHTML文件中的属性文件中获取值 [英] fetching the values from a property file inside a XHTML file
问题描述
我的本地文件系统中有一个属性文件. 我已使用XHTML文件创建UI. 在此文件中,我对UI元素的名称进行了硬编码.是否有任何方法可以从属性文件中获取这些名称?
I have a properties file in my local File system. I have used a XHTML file to create a UI. In this file I have hardcoded the names for UI elements.Is there any way to fetch those names from the properties file?
推荐答案
有两个选项,假设您在以下位置具有messages.properties
There are a couple of options, assume you have a messages.properties in the following location
src
main
java
resources
com
example
messages.properties
您可以在faces-config.xml
中使用resource-bundle
标记使其在整个应用范围内
You can use the resource-bundle
tag in the faces-config.xml
to make it application wide
<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中对其进行访问(请注意,使用语言环境使您可以选择具有messages_fr.properties)
Then it can be accessed in your XHTML like so (note the use of locale gives you the option of having a 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>
如果您需要将资源束设为外部,则可以采用以下方法.
If you need the Resource bundle to be external one way might be the following approach.
在web.xml中设置捆绑软件的绝对路径
Set the absolute path to your bundle in your web.xml
<context-param>
<param-name>bundlePath</param-name>
<param-value>absolute path to your properties file</param-value>
</context-param>
创建自己的ResourceBundle类
Create your own ResourceBundle class
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();
}
}
照常在faces-config.xml
中注册
<resource-bundle>
<bundleName>com.example.MyBundle</bundleName>
<var>msgs</var>
</resource-bundle>
这篇关于从XHTML文件中的属性文件中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!