background image

Using FacesMessage to Create a Message

<< Localizing Messages | Creating a Custom Converter >>
<< Localizing Messages | Creating a Custom Converter >>

Using FacesMessage to Create a Message

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" on page 399
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" on page 399
gives an example of accessing messages.
Using FacesMessage to Create a Message
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);
}
Performing Localization
The Java EE 5 Tutorial · September 2007
392