國際化(i18n)將頁面所有文字標籤集中至訊息資源檔,依使用者語系載入對應資源檔顯示,實現多語系支援。核心在於 <bean:message> 標籤搭配 MessageResources 機制。
<struts-config>
<form-beans>
<form-bean name="HelloForm" type="hello.HelloForm"/>
</form-beans>
<global-forwards>
<forward name="aerror" path="/public/jsp/ShowError.jsp"/>
<forward name="success" path="/public/jsp/ShowSuccess.jsp"/>
</global-forwards>
<action-mappings>
<forward name="sayHello" path="/hello.jsp"/>
</action-mappings>
<message-resources parameter="hello.ApplicationResources"/>
</struts-config>
<message-resources> 的 parameter 指向 classpath 下的 hello/ApplicationResources.properties。
; Application Resources
hello.title = 你好,歡迎光臨!
中文需轉碼為 Unicode 轉義序列,使用 JDK native2ascii 工具:
native2ascii -encoding gb2312 ApplicationResources.properties ApplicationResources_zh.properties
native2ascii 位於 $JAVA_HOME/bin,若提示找不到指令請檢查環境變數。ApplicationResources_zh.properties 含 Unicode 編碼(如 hello.title = \u4f60\u597d\uff0c\u6b22\u8fce\u5149\u81ea\uff01)。_zh(中文)、_en(英文)等,Struts 依 Locale 自動選取。<%@ page contentType="text/html;charset=gbk"%>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html:html locale="true">
<html:base/>
<h2><bean:message key="hello.jsp.page.heading"/></h2>
<html:errors/>
<logic:present name="helloForm" scope="request">
<h2>Hello <bean:write name="helloForm" property="person"/>!</h2>
</logic:present>
<html:form focus="person" action="helloWorld.do">
<bean:message key="hello.jsp.prompt.person">
<html:text property="person" maxlength="20" size="20"/><br>
<html:submit property="submit" value="提交"/>
<html:reset/>
</html:form><br>
<html:img page="/struts-power.jpg" alt="Powered by Struts"/>
</html:html>
<bean:message key="hello.title"> 從資源檔讀取對應鍵值顯示。<html:html locale="true"> 讓框架依瀏覽器語系自動切換資源檔。charset=gbk)需與資源檔編碼一致,否則顯示亂碼。struts-config.xml 設定 <message-resources> 基底名稱。.properties 及各語系 _zh.properties、_en.properties 等。native2ascii 將非 ASCII 字元轉碼。bean 標籤庫,用 <bean:message key="..."> 取值顯示。WEB-INF/classes/hello/)。???key???。native2ascii 轉碼。