12.5. Creating Localized Messages from an Action
Problem
You need to create a localized message from within an
Action.
Solution
MessageResources resources = getResources(request); Locale locale = getLocale(request); String msg1 = resources.getMessage(locale, "message.success")); String msg2 = resources.getMessage(locale, "msg.hello", "Bill"));
Discussion
Application messages for information and errors are typically created
using the ActionMessage and
ActionError classes. These messages are saved in
the request using the saveMessages( ) and
saveErrors( ) methods.
Warning
The ActionError class has been deprecated in
Struts 1.2. The ActionMessage class should be used
instead.
But you can retrieve localized text messages in the Action itself.
You may need the message in the Action because you
are logging this information or you need to pass the message to some
other service. The Solution shows how you can get a localized message
in an Action. The
MessageResources
and current Locale are retrieved using the
getResources( ) and getLocale() methods of the base Action class.
MessageResources provides a number of variations
of the getMessage( ) method. There are three basic
pieces of information you can pass:
-
locale The requested message
Localeor null for the system defaultLocale-
key The message key to look up
-
args An array of replacement parameters for placeholders in the message
You can retrieve messages from an alternate
MessageResources set. Suppose you've declared your alternate set in the ...