background image

Localizing Messages

<< Performing Localization | Using FacesMessage to Create a Message >>
<< Performing Localization | Using FacesMessage to Create a Message >>

Localizing Messages

text =
"???" + key + "???";
}
// Construct and add a FacesMessage containing it
context().addMessage(clientId, new FacesMessage(text));
}
This method gets the current locale from the UIViewRoot instance of the current request and
loads the localized data for the messages using the getBundle method, passing in the path to the
ResourceBundle
and the current locale.
The other backing beans call this method by using the key to the message that they are trying to
retrieve from the resource bundle. Here is a call to the message method from
tut-install/javaeetutorial5/examples/web/bookstore6/src/java/com/sun/bookstore6/backing/ShowCartBean.ja
message(null,
"Quantities Updated");
Localizing Messages
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" on page 448
includes an example of registering a
ResourceBundle
in the application configuration resource file.
Creating a Message with a Message Factory
To use a message factory to create a message, follow these steps:
1. Register the ResourceBundle instance with the application. This is explained in
"Registering
Custom Error Messages" on page 448
.
2. Create a message factory implementation. You can simply copy the MessageFactory class
included with the Duke's Bookstore application to your application.
3. 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.
Performing Localization
Chapter 12 · Developing with JavaServer Faces Technology
391