國際化(i18n)核心在於**依用戶語系環境動態選擇資源檔**。Struts 提供 <bean:message> 標籤自動依 Session Locale 載入對應屬性檔,並支援程式化切換語系。本文涵蓋編碼設定、資源檔命名規則、自動/手動切換兩大模式。
<%@ page contentType="text/html; charset=UTF-8" %><controller contentType="text/html; charset=UTF-8" />(僅對經由 .do/forward 的頁面生效)<meta http-equiv="content-type" content="text/html; charset=UTF-8">雖可從 Accept-Charset 取得客戶端偏好,但瀏覽器支援度不一,**UTF-8 為最佳通用方案**。
如 application.properties(預設)、application_zh.properties(中文)、application_en.properties(英文)、application_fr.properties(法文)。
application_zh_TW.properties(繁體中文)、application_en_AU.properties(澳洲英文)。
_(不可用連字號 -)。application_ZH_tw.properties。若瀏覽器語系為 zh-TW:
application_zh_TW.properties → application_zh.properties → application.properties
若語系為 zh(無國家碼):直接從 application_zh.properties 開始。
<bean:message><message-resources parameter="struts.application" key="global" />
parameter:資源檔基底路徑(對應 WEB-INF/classes/struts/application.properties)。key:束識別碼,使用時需指定 bundle="global"。<%@ taglib uri="https://struts.apache.org/tags-bean" prefix="bean" %>
<bean:message key="title" bundle="global" />
<form>
<bean:message key="name" bundle="global" />:<input name="name">
<input type="submit" value="<bean:message key='submit' bundle='global'/>" />
</form>
IE「網際網路選項 → 語言」新增「中文 [zh]」、「英文 [en]」、「法文 [fr]」、「梵文 [sa]」,依序移至最上方並重新整理頁面觀察切換效果。
titleKey、altKey 等 Key 尾綴屬性可直接引用資源鍵:<html:submit titleKey="title" bundle="global"/>value 屬性**不支援**直接引用鍵值,改用巢狀標籤:
<html:submit>
<bean:message key="submit" bundle="global"/>
</html:submit>
<%
if ("en".equals(request.getParameter("language")))
session.setAttribute("org.apache.struts.action.LOCALE", new java.util.Locale("en"));
else if ("zh".equals(request.getParameter("language")))
session.setAttribute("org.apache.struts.action.LOCALE", new java.util.Locale("zh"));
else if ("fr".equals(request.getParameter("language")))
session.setAttribute("org.apache.struts.action.LOCALE", new java.util.Locale("fr"));
%>
setLocale()setLocale(request, new java.util.Locale("zh", "TW")); // 語系、國家碼不分大小寫
注意:經由 <forward> 或 .do 的後續頁面會繼承新 Locale,**但 <action> 的 forward/input 屬性指向頁面除外**。
mainGlobal.jsp<a href="newGlobal.jsp?language=en" target="_blank">英文</a>
<a href="newGlobal.jsp?language=zh" target="_blank">中文</a>
<a href="newGlobal.jsp?language=fr" target="_blank">法文</a>
Struts 國際化機制:**UTF-8 編碼 + 標準資源檔命名 + <bean:message> 自動解析 + Session Locale 管理**。靜態語系依瀏覽器偏好自動切換;動態語系透過修改 Session 屬性 org.apache.struts.action.LOCALE 實現。掌握資源檔命名規範(底線、大小寫)是避免亂碼關鍵。