Mat*_*ler 13 jsf internationalization managed-bean
使用<resource-bundle>
文件我可以在我的JSF页面中使用i18n文本.
但是有可能在我的托管bean中访问这些相同的属性,所以我可以设置具有i18n值的面部消息吗?
Bal*_*usC 45
假设您已按如下方式配置它:
<resource-bundle>
<base-name>com.example.i18n.text</base-name>
<var>text</var>
</resource-bundle>
Run Code Online (Sandbox Code Playgroud)
如果你的bean的请求范围,你可以注入<resource-bundle>
的@ManagedProperty
由它<var>
:
@ManagedProperty("#{text}")
private ResourceBundle text;
public void someAction() {
String someKey = text.getString("some.key");
// ...
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您只需要一些特定的密钥:
@ManagedProperty("#{text['some.key']}")
private String someKey;
public void someAction() {
// ...
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您的bean在更广泛的范围内,则#{text}
在方法本地范围内以编程方式进行评估:
public void someAction() {
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle text = context.getApplication().evaluateExpressionGet(context, "#{text}", ResourceBundle.class);
String someKey = text.getString("some.key");
// ...
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您只需要一些特定的密钥:
public void someAction() {
FacesContext context = FacesContext.getCurrentInstance();
String someKey = context.getApplication().evaluateExpressionGet(context, "#{text['some.key']}", String.class);
// ...
}
Run Code Online (Sandbox Code Playgroud)
你甚至可以通过标准ResourceBundle
API 获得它,就像JSF本身已经在幕后做的那样,你只需要在代码中重复基本名称:
public void someAction() {
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle text = ResourceBundle.getBundle("com.example.i18n.text", context.getViewRoot().getLocale());
String someKey = text.getString("some.key");
// ...
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您通过CDI而不是JSF管理bean,那么您可以@Producer
为此创建一个:
public class BundleProducer {
@Produces
public PropertyResourceBundle getBundle() {
FacesContext context = FacesContext.getCurrentInstance();
return context.getApplication().evaluateExpressionGet(context, "#{text}", PropertyResourceBundle.class);
}
}
Run Code Online (Sandbox Code Playgroud)
并注入如下:
@Inject
private PropertyResourceBundle text;
Run Code Online (Sandbox Code Playgroud)
或者,如果您正在使用Messages
JSF实用程序库OmniFaces的类,那么您可以只设置其解析程序一次以让所有Message
方法都使用该包.
Messages.setResolver(new Messages.Resolver() {
public String getMessage(String message, Object... params) {
ResourceBundle bundle = ResourceBundle.getBundle("com.example.i18n.text", Faces.getLocale());
if (bundle.containsKey(message)) {
message = bundle.getString(message);
}
return MessageFormat.format(message, params);
}
});
Run Code Online (Sandbox Code Playgroud)
另请参阅javadoc和showcase页面中的示例.
归档时间: |
|
查看次数: |
22068 次 |
最近记录: |