Struts 透過 MessageResources 機制支援國際化:將不同語言文字放入對應的屬性檔,JSP 使用 <bean:message> 或 <s:text> 標籤,框架自動根據瀏覽器 Accept-Language 或 Session 中的 Locale 解析對應鍵值,實現零代碼侵入的多語言切換。
基礎名稱.properties # 預設語言(通常英文)
基礎名稱_zh_CN.properties # 簡體中文
基礎名稱_zh_TW.properties # 繁體中文
基礎名稱_en_US.properties # 美式英文
建議統一放置於 /WEB-INF/classes/resources/ 目錄,並在 struts-config.xml 配置:
<message-resources parameter="resources.ApplicationResources"/>
native2ascii 轉換為 Unicode 轉義格式:
native2ascii -encoding UTF-8 ApplicationResources.properties ApplicationResources_zh_CN.properties
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!-- Struts 1.x -->
<bean:message key="index.title"/>
<!-- Struts 2 -->
<s:text name="index.title"/>
MessageResources resources = getResources(request);
String msg = resources.getMessage(locale, "key");
request.setAttribute("dynamicMsg", msg);
其中 locale = (Locale) session.getAttribute(Globals.LOCALE_KEY)。
Locale newLocale = new Locale(language, country);
session.setAttribute(Globals.LOCALE_KEY, newLocale);
語言/國家代碼參考 Unicode 官方列表。
為每種語言準備對應版本圖片,路徑寫入資源檔:
# 資源檔
logo.path=/images/logo_zh_CN.png
JSP 引用:<img src="<bean:message key='logo.path'/>" />
後端繪圖時,靜態文字從資源檔讀取,動態數據直接拼裝,確保圖片內容隨語言切換。
Tomcat 預設 ISO-8859-1 解碼 URL 參數,導致中文亂碼。手動 new String(param.getBytes("ISO-8859-1"), "UTF-8") 繁瑣且易漏。
public class EncodingFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
chain.doFilter(req, resp);
}
}
web.xml 配置:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>com.example.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
一勞永逸解決所有請求(含 multipart)編碼問題。
CREATE DATABASE ... CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;?characterEncoding=utf8&useUnicode=trueVARCHAR / TEXT 存儲 UTF-8 內容。Struts 國際化核心在於「資源檔標準化 → native2ascii 轉換 → 框架自動解析 → Filter 統一編碼 → 資料庫字元集對齊」。遵循此全鏈路規範,即可構建支援多語言無縫切換的企業級應用。