1、Struts2國際化介紹
國際化即internationalization簡稱i18n.為了實現程序的國際化,必須先提供程序所需要的資源文件。資源文件的內容是key-value鍵值對。
資源文件的命名可以是如下3種形式:
其中baseName是資源文件的基本名稱,用戶可以自由定義,而language和country都不可隨意變化,必須是java所支持的語言和國家。
2、國際化資源文件的分類
Struts2提供了4種方式來加載國際化資源文件:1).全局范圍,可以放置在任意位置,但是必須要在struts.xml文件中通過常量引入資源文件。 baseName_language_country.properties.如message_zh_CN.properties
1 <!--這是在com.sunny.action包下-->2 <constant name="struts.custom.i18n.resources" value="com.sunny.action.message"></constant>3 <!--這是在src下--> 4 <constant name="struts.custom.i18n.resources" value="message"></constant>
2).包范圍,某個包下。
package_language_country.properties.如package_zh_CN.properties3).類范圍,在該類同一路徑下。 actionName_language_country.properties.如LoginAction_zh_CN.properties4).臨時資源文件,在jsp頁面使用<s:i18n>標記來指定classes路徑下的資源文件。
1 <s:i18n name="com.sunny.action.I18NAction">2 <s:text name="GOOD"></s:text>3 </s:i18n>
3、Struts2使用國際化消息
Struts2使用國際化消息主要在如下3種方式:
1)在JSP頁面中使用國際化消息,可以使用Struts2的<s:text…/>標簽,該標簽可以指定一個name屬性,該屬性指定了國際化資源文件中的key.
1 <s:text name="login.username"></s:text>2 <s:textfield name="username" key="login.username"></s:textfield>
還可以輸出帶占位符的信息,比如有一個 login.welcome = 你好{0},那么可以用下面這種方式來顯示:
<s:text name="login.welcome"> <s:param>username</s:param></s:text>
2)在Action類中使用國際化消息,可以使用ActionSupport類的getText()方法,該方法可以接受一個name參數,該參數指定了國際化資源文件中的key .
1 getText("login.username");
還可以使用帶占位符的信息。比如有一個 login.welcome = 你好{0},那么可以用下面這種方式來顯示:
1 String params[] = {"張三"};2 String welcome = getText("login.welcome", params);
3)在表單元Label里使用國際化信息,可以為該表單標簽指定一個key屬性, 該key指定了國際化資源文件中的key.
4、國際化實例
1)創建全局國際化資源文件
Login_zh_CN.properties
1 item.name=姓名2 item.passWord=密碼
Login_en_US.properties
1 item.name=name2 item.password=password
2)在struts.xml文件中配置國際化資源文件
1 <struts> 2 <constant name="struts.devMode" value="true" /> 3 <constant name="struts.custom.i18n.resources" value="Login" /> 4 5 <package name="default" namespace="/" extends="struts-default"> 6 <action name="i18nAction" class="com.sunny.action.I18NAction"> 7 <result>/input.jsp</result> 8 </action> 9 </package>10 11 </struts>
3)創建jsp頁面
1 <body>2 <a href="${pageContext.servletContext.contextPath}/i18nAction?request_locale=zh_CN">中文</a>3 <a href="${pageContext.servletContext.contextPath}/i18nAction?request_locale=en_US">English</a>4 <form action="${pageContext.servletContext.contextPath}/login.action">5 <s:textfield name="name" key="item.name"/><br>6 <s:textfield name="password" key="item.password"/><br>7 </form>8 </body>
4)jsp顯示界面
新聞熱點
疑難解答