I would like to be able to retrieve a string from a message bundle from inside a JSF 2 managed bean. This would be done in situations where the string is used as the summary or details parameter in a FacesMessage
or as the message in a thrown exception.
I want to make sure that the managed bean loads the correct message bundle for the user's locale. It is not clear to me how to do this from a managed bean using JSF API calls.
My configuration is:
- Using Tomcat 7 as the container so the solution cannot depend on API calls that only work in a full application server container
- Using the JSF 2 reference implementation (Mojarra)
- NOT using any libraries that allow CDI
NOTE: I did see this similar question, but it depends on features that are unavailable in my configuration
EDIT: I made a mistake in my original question. What I meant to ask was "How can I get a resource bundle string from inside a managed bean"? BalusC gave me the correct answer for what I asked. The solution for what I actually meant to ask is very similar:
public static String getResourceBundleString(
String resourceBundleName,
String resourceBundleKey)
throws MissingResourceException {
FacesContext facesContext = FacesContext.getCurrentInstance();
ResourceBundle bundle =
facesContext.getApplication().getResourceBundle(
facesContext, resourceBundleName);
return bundle.getString(resourceBundleKey);
}
Also, here is a link to another question that explains the difference between "message" bundles and "resource" bundles.
messageBundleName
is being set to null which causes aNullPointerException
in the call togetBundle()
. – Anglaangle