首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Struts 2 國際化 (i18n) 完整指南:資源檔搜尋順序、標籤用法與瀏覽器語系自動切換

     編輯:Java 相關知識

Struts 2 國際化核心機制

Struts 2 使用標準 Java .properties 資源檔,支援多層級搜尋順序,自動依瀏覽器 Accept-Language 選擇語系變體 (如 Message_zh_TW.properties)。

資源檔搜尋順序 (優先級高→低)

  1. ActionClass.properties:與 Action 類別同名、同目錄 (如 LoginAction.properties)
  2. BaseClass.properties:父類別同名檔 (需放在父類別包路徑下,如 ActionSupport.properties 放在 xwork2.jar!/com/opensymphony/xwork2/)
  3. Interface.properties:實作介面同名檔
  4. ModelDriven 模型類:若實作 ModelDriven,重複步驟 1 搜尋模型類同名檔
  5. package.properties:固定檔名,放在 Action 所在包或其父包任一層 (最近優先)
  6. I18n 內建資源:Struts 核心訊息 (驗證錯誤等)
  7. Global Resource:struts.properties 設定 struts.custom.i18n.resources=my → my.properties 放在 classpath 根目錄

實作範例

Action 類別

package action.test;
public class Internationalizing extends ActionSupport {
    public String execute() { return "forward"; }
}

資源檔 action/test/Internationalizing.properties

delete=刪除
save=保存

JSP 取用方式

<%@ taglib prefix="s" uri="/struts-tags" %>
<!-- 方式 1: property 標籤 -->
<s:property value="getText('delete')" />

<!-- 方式 2: text 標籤 (推薦) -->
<s:text name="save" />

<!-- 方式 3: i18n 標籤指定資源檔 -->
<s:i18n name="test.abc">  <!-- 對應 WEB-INF/classes/test/abc.properties -->
  <s:text name="save" />
  <s:text name="delete" />
</s:i18n>

全域資源檔設定

# struts.properties (放在 src/ 根目錄)
struts.custom.i18n.resources=my

# my.properties (放在 src/ 根目錄)
welcome=歡迎光臨

瀏覽器語系自動切換

提供同基底名稱的語系變體檔:

  • language.properties (預設)
  • language_en.properties (英文)
  • language_zh.properties (中文)
  • language_zh_TW.properties (繁體中文)

Struts 2 依 RequestLocale 攔截器解析 Accept-Language 標頭,自動選擇最匹配檔案。缺少對應變體時回退至基底檔。

IE 語言設定

最佳實務建議

  • 專案層級訊息:使用 Global Resource (struts.custom.i18n.resources) 集中管理
  • Action 專用訊息:使用 ActionClass.properties,隨類別移動
  • 套件共用訊息:使用 package.properties 放在套件目錄
  • 編碼:所有 .properties 儲存為 UTF-8 (或使用 native2ascii 轉 Unicode 逸出)
  • 鍵值命名:採用 模組.功能.訊息 格式 (如 user.login.failed) 避免衝突
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved