You are here

Getting a localized string from the resource bundle

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:

  1. public static String getMessageFromBundle(String bundle,String key) {
  2.    FacesContext ctx = getFacesContext();
  3.    try {
  4.     ResourceBundle bundle =
  5.      ResourceBundle.getBundle(bundle, ctx.getViewRoot().getLocale());
  6.         return bundle.getString(key);
  7.    }
  8.    catch (Exception e) {
  9.       return "";
  10.    }
  11. }
While the bundle parameters must be the name of the bundle defined in the faces-config:
  1. <resource-bundle>
  2.   <base-name>
  3.         yourBundle
  4.    </base-name>
  5.   <var>bundle</var>
  6. </resource-bundle>
  7. <message-bundle>
  8.      yourBundle
  9. </message-bundle>
If you want to add a message to the JSF Messages than you could use following example:
  1. String invalidName = getMessageFromBundle("yourBundle",
  2.                                        "invalid_name_message');
  3. JSFMessageUtils.addFacesErrorMessage(errorMessage);
Applies to: 


Hi Yannick, this worked perfectly for me and was exactly what I was looking for, great job.

Chris W

Theme by Danetsoft and Danang Probo Sayekti inspired by Maksimer