published by Yannick on 8 June, 2011 - 14:21
When you are working with multilingual applications, you will need to show all messages and labels in the language of the users. Therefore we use resource bundles.
When you define a resource budnle in the faces-config you can access it in any JSPX page but you also want to access it in a managed bean. This snippet shows you how:
Snippet:
public static String getMessageFromBundle(String bundle,String key) {
FacesContext ctx = getFacesContext();
try {
ResourceBundle bundle =
ResourceBundle.getBundle(bundle, ctx.getViewRoot().getLocale());
return bundle.getString(key);
}
catch (Exception e) {
return "";
}
}
While the bundle parameters must be the name of the bundle defined in the faces-config:
<resource-bundle>
<base-name>
yourBundle
</base-name>
<var>bundle</var>
</resource-bundle>
<message-bundle>
yourBundle
</message-bundle>
Example:
If you want to add a message to the JSF Messages than you could use following example:
String invalidName = getMessageFromBundle("yourBundle",
"invalid_name_message');
JSFMessageUtils.addFacesErrorMessage(errorMessage);
Comments
Getting a localized string from the resource bundle
Hi Yannick, this worked perfectly for me and was exactly what I was looking for, great job.
Chris W
Add new comment