Struts Message Resources
Overview:Many programmers who have just learned struts will encounter many difficulties when using the messageresources feature of struts. This article will try to explain the advantages of messageresources and give examples to illustrate its usage.
By Nick heudecker, System Mobile Inc.
Directory:
-
- Usage
- Create a resource package
- Configuration
- Where to place files
- Tag
- Actions
- Internationalization
- Jstl
- Conclusion
- About the author
- Resources
- Notes
Usage
To use the message resource package, you need to do the following:
- Create a message resource package where you want to support it.
- Configure the Web application and load the message resource package.
- Use the corresponding JSP tag to load resources or...
- ... Load resources in an action class.
[
Create a resource package
The default implementation of the messageresources class is a file containing the "Key = value" pair. The following is an example of a message resource package file.
label.username=Usernamelabel.password=Passwordlabel.first.name=First Namelabel.last.name=Last Namelabel.email=Email Addresslabel.phone.number=Phone Numberlabel.welcome=Welcome back {0} {1}!error.min.length=The input must be at least {0} characters in length.error.max.length=The input cannot be longer than {0} characters in length.
The integer enclosed by braces is a pairjava.text.MessageFormat
Class Support, the programmer can pass parameters to the value string, you can pass up to four parameters for each value string.
[
Configuration
There are two ways to notify struts of the location of your resource package:web.xml
File orstruts-config.xml
File. First, let's take a look at the configuration of the web. xml file:
<servlet><servlet-name>action</servlet-name><servlet-class> org.apache.struts.action.ActionServlet</servlet-class><init-param><param-name> application</param-name><param-value> com.systemmobile.example.ApplicationResources</param-value></init-param></servlet>
This configuration indicates that your resource package name isApplicationResources.properties
, It is located incom.systemmobile.example
Package. The suffix ". properties" is implicit and you do not need to explicitly write it out. If you have another resource file in the same package, for exampleApplicationResources_fr.properties
To support French, you only need to list file names as defined above.
The method in the second definition of the resource file (as mentioned above) isstruts-config.xml
File Configuration:
<message-resources parameter="com.systemmobile.example.ApplicationResources"/>
Attributeparameter
Is required. Andweb.xml
The configuration in the file is the same. Note the location of the file in the package.
Usestruts-config.xml
File to configure message resource files is recommended because it is more scalable and flexible.
- You can use
message-resources
The tag retrieves different messages from different resource files, provided that different resource files are provided during configuration.key
Attribute Value. For example:<message-resources key="myResources" parameter="com.systemmobile.example.ApplicationResources"/><message-resources key="moreResources" parameter="com.systemmobile.example.MoreApplicationResources"/>
Then you must usebean:message
Tags:
<bean:message bundle="moreResources" key="some.message.key"/>
- Set attributes
null
If a resource string does not exist??? Key ???Instead of simply displayingNull. In this way, you can easily see the resources you have not defined on the JSP page, making internal testing faster. (For details about how to obtain messages from resource files, see
- In addition,
message-resources
Tag allows you to use your ownMessageResourcesFactory
Interface, which is not in the scope of this article.
[Return]
Where are resource files stored?
The most common problem with resource files is where the resource files are stored in war files. The simple answer is that the file must be placed under your classpath, which means to put the resource file in a jar file or/WEB-INF/classes
Sub-directories. The following table shows the location of the resource file.message-resources
The value of the "parameter" attribute in the tag and a brief description.
Resources location |
parameter Value |
Description |
// WEB-INF/classes/applicationresources. Properties |
ApplicationResources |
Put the file in the classes Directory, which is in the classpath of the Web application. |
// WEB-INF/classes/resources/applicationresources. Properties |
resources.ApplicationResources |
This file is placed in the "Resources" directory, so the package name, that is, the path name, must be provided. [1] |
In the app. jar file, in the com. systemmobile. Example package/directory. |
com.systemmobile.example.ApplicationResources |
The full path of the file in the jar file. |
[
Tags
The most common struts tag isbean:message
Label. The "key" of this tag can be used to read specific message resources from the resource file. You can also input one or all of the four parameters:
<bean:message key="label.password"/><bean:message key="error.min.length" arg0="6"/><bean:message key="label.welcome" arg0="Ralph" arg1="Nader"/>
html:message
This allows you to Display error messages (default) or message information to users.html:errors
Only the error message is displayed. Obviously, the error message or message information must be stored in the request, otherwise nothing will be displayed. Here is an example of displaying message information:
<logic:messagesPresent message="true">
Some tags are also limited to support message resources, suchhtml:link
.html:link
The label displays the title text by defining the "titlekey" attribute. Manyhtml
Use the "altkey" attribute to obtain the alternate text from the resource file.
[
Actions
You can also use the message resource file in the action class. The action class has two methods to getMessageResource
Class instance:
// Return the resource file protected messageresources getresources (httpservletrequest request) in a request; // return the resource file in a request, // The content of the <message-resources/> element protected messageresources getresources (javax. servlet. HTTP. httpservletrequest request, Java. lang. string key );
The messageresources class allows you to obtain localized messages from resource files. The APIMessageResources
You can
// these methods load a resources key for the given localepublic String getMessage(java.util.Locale locale, java.lang.String key);public String getMessage(java.util.Locale locale, java.lang.String key, java.lang.Object arg0);public String getMessage(java.util.Locale locale, java.lang.String key, java.lang.Object[] args);public String getMessage(java.util.Locale locale, java.lang.String key, java.lang.Object arg0, java.lang.Object arg1)public String getMessage(java.util.Locale locale, java.lang.String key, java.lang.Object arg0, java.lang.Object arg1, java.lang.Object arg2);public String getMessage(java.util.Locale locale, java.lang.String key, java.lang.Object arg0, java.lang.Object arg1, java.lang.Object arg2, java.lang.Object arg3);// these methods load a resources key for the locale retrieved// from the HttpServletRequestpublic String getMessage(java.lang.String key);public String getMessage(java.lang.String key, java.lang.Object arg0);public String getMessage(java.lang.String key, java.lang.Object[] args);public String getMessage(java.lang.String key, java.lang.Object arg0, java.lang.Object arg1);public String getMessage(java.lang.String key, java.lang.Object arg0, java.lang.Object arg1, java.lang.Object arg2);public String getMessage(java.lang.String key, java.lang.Object arg0, java.lang.Object arg1, java.lang.Object arg2, java.lang.Object arg3);
These returned strings can be set as request or session parameters, and the string will represent the layer. You may have noticed some overload methods.getMessage(...)
Parameter SelectedObject
And other parameters are used.arg0...arg3
. This andbean:message
arg0...arg3
Attribute equivalence.
BesidesMessageResources
Class, some classes use resource files.ActionMessage
Class is used to transmit the keys in the message resource from the action to the JSP. Messages are used as bean attributes.ActionError
,ActionMessage
Using the keys in the message resource to store error messages after verification fails.
[Return]
Internationalization
Extract a localized information from the resource file.MessageResources
Or its direct subclass propertymessageresources class. Since the class propertymessageresources is often used, let's take a look at how it is usedgetMessage(Locale, String)
Method To read messages from the resource file.
- Example:
ApplicationResources_pt_br.properties
(Receivilian Portuguese ).ApplicationResources_pt.properties
File, ifApplicationResources_pt.properties
If the file does not exist or the message does not exist, goApplicationResources.properties
File.
- If the message is found, it is added to the localized cache and returns
java.lang.String
Type data.
- If the message is not found, if
returnNull
If the property is set to the default value "true ",null
. Otherwise, a message similar??? Key ???String,KeyIs the passed parameter.
[
Jstl
Jstl (assumerver pages standard tag Library)fmt
Tags have recently become popular and are used to display the information of resource files in JSP. It can be well integrated with struts. It is very easy to use, as long as you download the jstl jar files and TLDs and copy them to the correct location of your application, and then inweb.xml
Add the following content to the file:
<context-param> <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name> <param-value>ApplicationResources</param-value></context-param>
The above configuration assumes that yourApplicationResources.properties
Files are stored in/WEB-INF/classes
Directory. See
Then place the tag library directly in your JSP:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
Finally, the following tag displays the content of the resource file:
<fmt:message key="label.first.name"/>
Another usefmt
Tag to obtain resources. (Note: This program is taken from Jakarta jstl examples .)
// loading a resource from a specific bundle and populating a parameter<fmt:message key="currentTime" bundle="${deBundle}"> <fmt:param value="${currentDateString}"/></fmt:message>// using the forEach iterator to populate paramters<fmt:message key="serverInfo" bundle="${deBundle}"> <c:forEach var="arg" items="${serverInfoArgs}"> <fmt:param value="${arg}"/> </c:forEach></fmt:message>
[Return]
Conclusion
While easily passing messages to JSP files, Struts uses the message resource file to help us create an international web application. We can either use the rapidly developing jstl tag, or use the struts tag, or directly obtain a specific message in the action. I hope this article will clarify some common but sometimes confusing things in struts.
[
About the author
Nick heudecker is a software developer with six years of enterprise application development experience. His company, system mobile, inc., specializes in Application Integration, custom software development, and wireless applications. He is also a sun-certified Java programmer and now lives in Ann Arbor and Michigan.
[
Resources
The following resources may help you learn more about struts resource files:
- Javadoc for the classes of interest:
-
- Java. util. locale
- Org. Apache. Struts. util. messageresources
- Org. Apache. Struts. Action. actionerror
- Org. Apache. Struts. Action. actionmessage
- Ted husted's struts tips: Very handy advice, especially for resource bundle usage.
- Struts Home Page
- Struts-user mailing list archive: Login people use struts, so there is a very good chance that your question has be answered already. please use all available resources before asking your question on the mailing list.
- Jstl homepage and the Jakarta jstl implementation
[Return]
Notes
- Packages are just directory structures used to avoid naming conflicts. If you put a message bundle in a directory named
resources
Under/WEB-INF/classes
, This is the equivalent of putting the file in a package namedresrouces
. While basic, this point seems to trip up when new programmers.
Java. util. resourcebundle return] Return] more situations of above. Top] resources. Common methods include: Return] internationalization)
<message-resources parameter="com.systemmobile.example.ApplicationResources" null="false"/>
Return]
Overview
Messageresources allows developers to easily support multiple languages, including multi-time and digital formats. Another advantage of using a resource package is that developers can store tag strings in one location rather than in different JSP pages. For example, for the label "first name" of each user's name, we can write it in the resource package and simply reference it through the struts tag in a proper place:
<bean:write key="label.first.name"/>
This will make it easier for you to change the program, and you do not have to change the TAG content on every JSP page.
Overview