|
Recipe 12.5. Creating Localized Messages from an ActionProblemYou need to create a localized message from within an Action. SolutionMessageResources resources = getResources(request); Locale locale = getLocale(request); String msg1 = resources.getMessage(locale, "message.success")); String msg2 = resources.getMessage(locale, "msg.hello", "Bill")); DiscussionApplication 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.
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:
You can retrieve messages from an alternate MessageResources set. Suppose you've declared your alternate set in the struts-config.xml file: <message-resources key="alt" parameter="AlternateResources"> </message-resources The getresources( ) method takes an optional parameter specifying the name of the MessageResources bundle, identified by the key attribute of the message-resources element: MessageResources resources = getResources(request, "alt"); If you only have access to the servlet request, you can create messages but you have to get the Locale and MessageResources through different means. To get the Locale, use the RequestUtils class in the org.apache.struts.util package: Locale locale = RequestUtils.getUserLocale(request, null); The default set of MessageResources can be retrieved using: MessageResources resources = (MessageResources) request.getAttribute(Globals.MESSAGES_KEY)); You can use one of the MessageResources.getMessage() methods to retrieve the message. You can retrieve an alternate set of MessageResources, but the code is more involved because modules are taken into account. Take a look at the source for the Action class if you're interested. See AlsoThe JavaDocs for the Struts Action class (http://struts.apache.org/api/org/apache/struts/action/Action.html) provide details on the convenience methods used in this recipe. |
|