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

Struts 2 國際化 (i18n) 資源配置完整指南

     編輯:Java 相關知識

資源檔命名規則

基礎名_語言_國家.properties   例:messages_zh_CN.properties
基礎名_語言.properties           例:messages_zh.properties
基礎名.properties                例:messages.properties (預設回退)

語言代碼符合 ISO-639,國家代碼符合 ISO-3166。可透過 Locale.getAvailableLocales() 獲取支援列表。

struts.xml 全域配置

<constant name="struts.custom.i18n.resources" value="messages"/>
<!-- 多資源檔以逗號分隔:value="messages,errors,labels" -->

JSP 頁面取值方式

1. <s:text> 標籤

<s:text name="username"/>
<s:text name="welcome">
    <s:param>${userName}</s:param> <!-- 佔位符 {0} -->
</s:text>

2. 表單標籤 key 屬性

<s:textfield name="user.name" key="username.label"/>
<!-- 自動查找 key 對應資源檔值作為 label -->

注意:若設定 struts.ui.theme=simple,key 屬性可能失效。

3. JSTL fmt 標籤庫

<%@ taglib prefix="fmt" uri="https://java.sun.com/jsp/jstl/fmt" %>
<fmt:setLocale value="zh_CN" scope="request"/>
<fmt:setBundle basename="messages" var="msg"/>
<fmt:message key="username" bundle="${msg}"/>

Action 類中程式化獲取

public class UserAction extends ActionSupport {
    public String execute() {
        String msg = getText("username.error"); // 純文字
        String formatted = getText("welcome.msg", new String[]{"Admin", "系統"}); // 含參數
        return SUCCESS;
    }
}

資源檔作用域與加載優先級

  1. Action 級:ActionName_zh_CN.properties(同目錄)
  2. Package 級:package_zh_CN.properties(套件目錄,遞歸向上查找)
  3. Global 級:struts.custom.i18n.resources 指定的基礎名

查找順序:Action 級 → Package 級(由下而上) → Global 級(依語言/國家/基礎名回退)。

佔位符參數傳遞


welcome.msg=歡迎 {0},您的角色是 {1}


<s:text name="welcome.msg">
    <s:param>${userName}</s:param>
    <s:param>${userRole}</s:param>
</s:text>


getText("welcome.msg", new String[]{userName, userRole});

最佳實踐

  • 資源檔統一使用 UTF-8 編碼,建議用 IDE 插件或 native2ascii 轉義非 ASCII 字元。
  • 基礎名建議按模組劃分(如 user-messages, order-messages),避免單一巨型檔案。
  • 生產環境啟用 struts.i18n.reload=true 開發模式熱載入,正式環境關閉提升效能。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved