Struts 2 內建強大的國際化支援,基於 ResourceBundle 機制,結合攔截器實現請求級別的語言環境切換。本文詳細說明三種資源文件作用域、JSP/Action 中使用、前端中英文動態切換完整實現。
| 作用域 | 命名格式 | 放置位置 | 生效範圍 |
|---|---|---|---|
| Action 級 | ActionName_zh_CN.properties | Action 類同包目錄 | 僅該 Action |
| 包級 | package_zh_CN.properties | 包根目錄(src 下對應包) | 該包下所有 Action |
| 全局級 | baseName_zh_CN.properties | src 根目錄 | 整個應用 |
優先級: Action 級 > 包級 > 全局級(同 key 時優先使用優先級高者)。
# resource_zh_CN.properties
login.title=用戶登錄
login.username=用戶名
login.psd=密碼
login.submit=登錄
login.welcome=歡迎 {0}
# resource_en_US.properties
login.title=User Login
login.username=Username
login.psd=Password
login.submit=Login
login.welcome=Welcome {0}

# struts.properties (src 根目錄)
struts.custom.i18n.resources=resource

<%@ taglib prefix="s" uri="/struts-tags" %>
<!-- 直接輸出文本 -->
<s:text name="login.title" />
<!-- 表單欄位自動取 label -->
<s:textfield name="username" key="login.username" />
<s:password name="psd" key="login.psd" />
<s:submit key="login.submit" />
<!-- 帶參數訊息:login.welcome=歡迎 {0} -->
<s:text name="login.welcome">
<s:param><s:property value="username" /></s:param>
</s:text>
public class LoginAction extends ActionSupport {
public String execute() {
// 簡單文本
String title = getText("login.title");
// 帶參數文本
String welcome = getText("login.welcome", new String[]{"張三"});
// welcome = "歡迎 張三"
return SUCCESS;
}
}
<a href="lang.action?request_locale=zh_CN">中文</a>
<a href="lang.action?request_locale=en_US">English</a>
<s:form id="loginform" action="login" method="post">
<s:textfield name="username" key="login.username" />
<s:password name="psd" key="login.psd" />
<s:submit key="login.submit" />
</s:form>
<action name="lang" class="com.example.action.HelloAction">
<result name="success">/index.jsp</result>
</action>
HelloAction 僅需返回 SUCCESS,實際切換由 i18n 攔截器(defaultStack 內建)自動處理:讀取 request_locale 參數,設置 ActionContext.getContext().setLocale()。

資源文件:error.msg=操作失敗:{0},錯誤碼:{1}
<!-- JSP -->
<s:text name="error.msg">
<s:param>資料庫連接超時</s:param>
<s:param>500</s:param>
</s:text>
<!-- Action -->
getText("error.msg", new String[]{"資料庫連接超時", "500"});
基礎名_語言_國家.propertiesstruts.custom.i18n.resources 指定全局基礎名<s:text>、key 屬性;Action 用 getText()request_locale 參數 + i18n 攔截器,無需手寫邏輯Struts 2 國際化機制簡單易用,適合中小型專案快速實現多語言支援。