Internationalization of struts2

Source: Internet
Author: User
Tags i18n

The following describes the com. opensymphony. xwork2.actionsupport. gettext () method.
Public String gettext (string atextname)
Note:Gets a messages based on a Message key, or null if no message is found
Parameters: atextname-The resource bundle key that is to be searched

ObtainKeyIf the message is not found, returnNull
Parameters:AtextnameIs matched in the Resource PackageKey
Summary: This method is used to complete internationalization. The received parameter isKey, Return toValue
Public String gettext (string atextname, list ARGs)
Note:Gets a message based on a key using the supplied ARGs, as defined in messageformat
Use the providedMessageformatParameters inARGsObtainKeyMessage
Summary:KeyThe value can beWith Parameters, That is{0}Placeholder. this parameter is provided by list args.
In other words, some runtime parameters can be passed so that the message generation isDynamic
In addition, there is a function that is the same as this method.Public String gettext (string key, string [] ARGs)
Only the list parameter method can receiveObjectParameter, while the array parameter method can only receiveString
In fact, when an object-type parameter is actually output to a page, it is also calledTostring ()Convert to string
Public String gettext (string atextname, string defaultvalue)
Note:Gets a message based on a key, if the message is not found, a supplied default value is returned
Summary: When in the Resource PackageKey not foundWillReturn defavalue Value

Three survival ranges of international resource files in struts2
Struts2 providesMore refinedResource file definition method, can be dividedGlobalAndPartial
Local international resource files can be divided into two types:Package levelAndClass Level
Package-level resource files are requiredCreate under the corresponding packageIts name is fixedPackage_zh_cn.properties
If the same key existsPackage levelToHigherGlobalResource file prompts
This is like Java. If a member variable with the same name and a local variable are defined, the member variable will be overwritten.
Class-level resource files are also requiredBuilt under the corresponding packageThe name is similarLoginaction_zh_cn.properties
The prompt information at the category level is more specific, soClass LevelToHigherPackage levelResource file prompt information

Trigger points of class-level and package-level in applications
To display international information in the form, remove<S: Form/>OfTheme = "simple"Attribute
Change the name field<S: textfield name = "username" Key = "username. xml. Invalid"/>
When accessing the page, it will be displayed in the name locationPackage levelPrompt information, that isPackage_zh_cn.propertiesIn
When you click SubmitWill be displayed in the name locationClass LevelDo not prompt information, that isRegisteraction_zh_cn.propertiesIn
After you click submit, the form isStruts. xmlSet inActionAssociation, so the class level prompt information is displayed
So whenUsage class levelInternational files are requiredTakes effect only after actionIn order to internationalize as scheduled
If you directly access the JSP page without action, you cannot display international messages at the category level.Struts1.xIs different

Nested ognl expressions in international resource files
The content in the international resource file is as follows:
Login. Text =Login
Login. Title =% {Gettext ("login. Text ")}Page
In this caseLogin. TitleWhen the message is internationalized, the following message is displayed:Logon page

International display on the page
<S: Text name = "key"/>The system automatically searches for the key specified by name in the resource file according to the range.
Then output the value corresponding to the key. If the key does not exist, the name valueUnchanged output
And it can also dynamically PASS Parameters. In this case, you need to nest the tag<S: Param/>Tag
<S: Label key = ""/>When the international text is output,Extra colon
You can view the source file on the page and find that: Use<S: Label/>The output international information is locatedHTML <label/>Label
Use<S: text/>The output international information isSimple text
<S: i18n name = ""/>Used to explicitly specify the temporary international resource files used
And the temporary resource file defaultsStruts. xmlIn the same directory, you can alsoNameSpecifies its storage path
Its name value is used to specify the international resource file to be read, and then nested<S: text/>The tag can output the specified key value.
In<S: Param/>To display international information, as shown in<S: Param value = "% {gettext ('login. Tip ')}"/>
In<S: Param/>The property of the received action is as follows:<S: Param value = "% {username}"/>
Struts2 form tagKey AttributeIt is usually used to output international information and can be transmitted in the key valueOgnlExpression
WhileLabel attributeIs a string, so you can also use% {}Output international information, as shown below
<S: property value = "gettext ('key')"/>Or<S: textfield label = "% {gettext ('key')}"/>
In addition, the <s: Radio/> label is displayed as follows:
<S: Radio list = "# {1: gettext ('i18n. sex. male '), 0: gettext ('i18n. sex. female ')} "name =" sex "value =" 1 "Key =" i18n. sex "/>
At this time, you do not need to write it again.% {Gettext ('i18n. Sex. Male ')}That is to say, you can% {}Removed
Because<S: textfield label = "% {gettext ('key')}"/>OfLabelBy defaultString, So you mustAdd % {}
In<S: Radio/>OfList attributeIt already has{}It indicates that it is alreadyOgnlExpression
Therefore<S: Radio list = "#{}"/>No need to use% {}Now

Brief Introduction to the implementation process of struts2 Internationalization
Struts2I18ninterceptor interceptorAll actions are intercepted.
From the request parameter sent by the client, check whether the name isRequest_localeParameters
If yesValueConvertLocaleSave
The Locale is saved inWw_trans_i18n_localeTheSessionInside
For details, see the source codeRow 3 session. Put (attributename, locale)
WhereAttributenameThat is, the 79 rowsProtected string attributename = default_session_attribute
And 75th rowsPublic static final string default_session_attribute = "ww_trans_i18n_locale"
Therefore, you can use this method to select the language environment displayed on the page.
For example, if you select Chinese, you can setRequest_localeSetZh_cn
If no configuration is made, the client will not send the request_locale parameter.
It usesGetlocale () of the request ()Method to get the default locale, save it in the session
In this way, all subsequent operations of the customer will be performed in the same international environment.
We do not need to manually judge the user's international environment every time.

The following shows the sample code.

The first is the Struts. xml file.

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <! Doctype struts public "-// Apache Software Foundation // DTD struts configuration 2.1/EN" <br/> "http://struts.apache.org/dtds/struts-2.1.dtd"> </P> <p> <struts> <br /> <constant name = "struts. custom. i18n. resources "value =" message "/> <br/> <package name =" struts2.1 "extends =" struts-Default "> <br/> <action name =" Internationalization "Class = "com. jadyer. action. internationalizationaction "> <br/> <result> loginsuccess. JSP </result> <br/> <result name = "input"> internationalization. JSP </result> <br/> </Action> <br/> </package> <br/> </struts>

Then the web. xml file

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <web-app version = "2.5" xmlns = "http://java.sun.com/xml/ns/javaee" <br/> xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" <br/> xsi: schemalocation = "http://java.sun.com/xml/ns/javaee <br/> http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <br/> <filter-Name> struts2 </filter-Name> <br/> <Filter -Class> Org. apache. struts2.dispatcher. ng. filter. strutsprepareandexecutefilter </filter-class> <br/> </filter> <br/> <filter-mapping> <br/> <filter-Name> struts2 </filter-Name> <br/> <URL-pattern>/* </url-pattern> <br/> </filter-mapping> <br/> <welcome-file-List> <br /> <welcome-File> internationalization. JSP </welcome-File> <br/> </welcome-file-List> <br/> </Web-app>

The internationalization. jsp page used to display International Information

<% @ Page Language = "Java" pageencoding = "UTF-8" %> <br/> <% @ taglib prefix = "S" uri = "/Struts-tags" %> <br/> <strong> <br/> <a href = "internationalization. action? Request_locale = zh_cn "> <s: Text name =" Internationalization. jsp. Chinese "/> </a> | <br/> <a href =" Internationalization. Action? Request_locale = en_us "> <s: Text name =" internationalization. JSP. english "/> </a> <br/> </strong> </P> <p> <HR/> </P> <p> <strong> <br/> <font color = "green"> <br/> <s: i18n name = "com. jadyer. action. temp "> <br/> <s: Text name =" hello "> <br/> <s: param> Xuan Yu </s: param> <br/> </S: Text> <br/> </s: i18n> <br/> </font> <br/> </strong> </P> <p> <HR/> </P> <p> <H4> initial the name and password are <font color = "blue"> <B> admin </B> </font> and <font color = "blue"> <B> jadyer </B> </font> </H4> </P> <p> <s: fielderror cssstyle = "font-size: 20px; color: red; text-align: Left; font-weight: bold"/> </P> <p> <s: form Action = "Internationalization" theme = "simple"> <br/> <Table border = "9"> <br/> <tr> <br/> <TD> <s: property value = "gettext ('internationalization. JSP. username ') "/> </TD> <br/> <TD> <s: textfield name = "username"/> </TD> <br/> </tr> <br/> <TD> <s: text name = "internationalization. JSP. passwrod "/> </TD> <br/> <TD> <s: password name = "password"/> </TD> <br/> </tr> <br/> <TD> </TD> <br /> <TD align = "center"> <s: submit/> </TD> <br/> </tr> <br/> </table> <br/> </S: Form>

Go to the loginsuccess. jsp page after successful access

<% @ Page pageencoding = "UTF-8" %> <br/> <H2> login success </H2>

Then the internationalizationaction. Java class is used.

Package COM. jadyer. action; </P> <p> Import COM. opensymphony. xwork2.actionsupport; </P> <p> @ suppresswarnings ("serial") <br/> public class internationalizationaction extends actionsupport {<br/> private string username; <br/> private string password; </P> <p> // getter and setter methods for username and password attributes </P> <p> @ override <br/> Public String execute () throws exception {<br/> If ("admin ". equals (this. getUserName (). trim ()) & "Jadyer ". equals (this. getPassword (). trim () {<br/> return success; <br/>}else {<br/> This. addfielderror ("username", this. gettext ("username. password. error "); <br/> return input; <br/>}</P> <p>/** <br/> * List list = new arraylist (); <br/> * List. add (username); <br/> * This. addfielderror (this. gettext ("username. invalid ", list); <br/> * we recommend that you use the string [] array. Because it is placed as a string parameter, It is very convenient <br/> * using addactionerror () to internationalize is the same as addfielderror, <br/> */<br/> @ override <br/> Public void validate () {<br/> If (null = username | username. length () <4 | username. length ()> 10) {<br/> This. addfielderror ("username", this. gettext ("username. invalid ", new string [] {username}); <br/>}< br/>}

 

Used to test the temp_zh_cn_en_us.properties international resource file used by the <s: i18n>, <s: Text>, and <s: param> labels.

 

Hello =/u4f60/u597d/u3010 {0}/u3011/u3002/u8fd9/u662f/users/u5d4c/u5957text/u6807/u7b7e/users/ u51fa/u7684/u7ed3/u679c </P> <p> Hello = Hello/u3010 {0}/u3011/u3002this is used the struts2 i18n with text tag to result

Finally, the global message_zh_cn.properties and message_en_us.properties are used as international resource files.

Internationalization. JSP. chinese =/u4e2d/u6587/u7248 <br/> internationalization. JSP. english =/u82f1/u6587/u7248 <br/> internationalization. JSP. passwrod =/u5bc6/u7801 <br/> internationalization. JSP. username =/u7528/u6237 <br/> username. invalid =/u7528/u6237/u540d "{0}"/u586b/u5199/u4e0d/u6b63/u786e <br/> username. password. error =/u7528/u6237/u540d/u6216/u5bc6/u7801/u4e0d/u6b63/u786e </P> <p> internationalization. JSP. chinese = Chinese <br/> internationalization. JSP. english = English <br/> internationalization. JSP. passwrod = PASSWORD <br/> internationalization. JSP. username = username <br/> username. invalid = username "{0}" invalid <br/> username. password. error = username or password Error

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.