The JavaServer Faces API provides two ways to create messages from a resource bundle:
You can register the ResourceBundle instance with the application configuration resource file and use a message factory pattern to examine the ResourceBundle and to generate localized FacesMessage instances, which represent single localized messages. The message factory pattern is required to access messages that are registered with the Application instance. Instead of writing your own message factory pattern, you can use the one included with the Duke’s Bookstore application. It is called MessageFactory and is located in tut-install/javaeetutorial5/examples/web/bookstore6/src/java/com/sun/bookstore6/util/.
You can use the FacesMessage class to get the localized string directly from the ResourceBundle instance.
Registering Custom Error Messages includes an example of registering a ResourceBundle in the application configuration resource file.
To use a message factory to create a message, follow these steps:
Register the ResourceBundle instance with the application. This is explained in Registering Custom Error Messages.
Create a message factory implementation. You can simply copy the MessageFactory class included with the Duke’s Bookstore application to your application.
Access a message from your application by calling the getMessage(FacesContext, String, Object) method of the MessageFactory class. The MessageFactory class uses the FacesContext to access the Application instance on which the messages are registered. The String argument is the key that corresponds to the message in the ResourceBundle. The Object instance typically contains the substitution parameters that are embedded in the message. For example, the custom validator described in Implementing the Validator Interface will substitute the format pattern for the {0} in this error message:
Input must match one of the following patterns {0} |
Implementing the Validator Interface gives an example of accessing messages.
Instead of registering messages in the application configuration resource file, you can access the ResourceBundle directly from the code. The validateEmail method from the Coffee Break example does this:
... String message = ""; ... message = CoffeeBreakBean.loadErrorMessage(context, CoffeeBreakBean.CB_RESOURCE_BUNDLE_NAME, "EMailError"); context.addMessage(toValidate.getClientId(context), new FacesMessage(message)); ...
These lines also call the loadErrorMessage to get the message from the ResourceBundle. Here is the loadErrorMessage method from CoffeeBreakBean:
public static String loadErrorMessage(FacesContext context, String basename, String key) { if ( bundle == null ) { try { bundle = ResourceBundle.getBundle(basename, context.getViewRoot().getLocale()); } catch (Exception e) { return null; } } return bundle.getString(key); }