Struts Message Resources

Source: Internet
Author: User

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:

  1. Create a message resource package where you want to support it.
  2. Configure the Web application and load the message resource package.
  3. Use the corresponding JSP tag to load resources or...
  4. ... 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.MessageFormatClass 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.xmlFile orstruts-config.xmlFile. 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.examplePackage. 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.propertiesTo 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.xmlFile Configuration:

<message-resources parameter="com.systemmobile.example.ApplicationResources"/>

AttributeparameterIs required. Andweb.xmlThe configuration in the file is the same. Note the location of the file in the package.

Usestruts-config.xmlFile to configure message resource files is recommended because it is more scalable and flexible.

  • You can usemessage-resourcesThe tag retrieves different messages from different resource files, provided that different resource files are provided during configuration.keyAttribute 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:messageTags:

    <bean:message bundle="moreResources" key="some.message.key"/>
  • Set attributesnullIf 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-resourcesTag allows you to use your ownMessageResourcesFactoryInterface, 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/classesSub-directories. The following table shows the location of the resource file.message-resourcesThe value of the "parameter" attribute in the tag and a brief description.


Resources location parameterValue 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:messageLabel. 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:messageThis allows you to Display error messages (default) or message information to users.html:errorsOnly 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:linkThe label displays the title text by defining the "titlekey" attribute. ManyhtmlUse 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 getMessageResourceClass 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 APIMessageResourcesYou 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 SelectedObjectAnd other parameters are used.arg0...arg3. This andbean:message arg0...arg3Attribute equivalence.

BesidesMessageResourcesClass, some classes use resource files.ActionMessageClass is used to transmit the keys in the message resource from the action to the JSP. Messages are used as bean attributes.ActionError,ActionMessageUsing the keys in the message resource to store error messages after verification fails.

[Return]

Internationalization

Extract a localized information from the resource file.MessageResourcesOr 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.

  1. Example:ApplicationResources_pt_br.properties(Receivilian Portuguese ).ApplicationResources_pt.propertiesFile, ifApplicationResources_pt.propertiesIf the file does not exist or the message does not exist, goApplicationResources.propertiesFile.
  2. If the message is found, it is added to the localized cache and returnsjava.lang.StringType data.
  3. If the message is not found, ifreturnNullIf 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)fmtTags 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.xmlAdd 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.propertiesFiles are stored in/WEB-INF/classesDirectory. 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 usefmtTag 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
  1. Packages are just directory structures used to avoid naming conflicts. If you put a message bundle in a directory namedresourcesUnder/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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.