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

Struts 國際化(i18n)實戰教學:從配置到多語系切換完整流程

     編輯:Java 相關知識

Struts i18n 運作原理

國際化(i18n)將頁面所有文字標籤集中至訊息資源檔,依使用者語系載入對應資源檔顯示,實現多語系支援。核心在於 <bean:message> 標籤搭配 MessageResources 機制。

一、struts-config.xml 設定資源檔路徑

<struts-config>
    <form-beans>
        <form-bean name="HelloForm" type="hello.HelloForm"/>
    </form-beans>
    <global-forwards>
        <forward name="aerror" path="/public/jsp/ShowError.jsp"/>
        <forward name="success" path="/public/jsp/ShowSuccess.jsp"/>
    </global-forwards>
    <action-mappings>
        <forward name="sayHello" path="/hello.jsp"/>
    </action-mappings>
    <message-resources parameter="hello.ApplicationResources"/>
</struts-config>

<message-resources> 的 parameter 指向 classpath 下的 hello/ApplicationResources.properties。

二、建立資源檔(ApplicationResources.properties)

; Application Resources
hello.title = 你好,歡迎光臨!

中文需轉碼為 Unicode 轉義序列,使用 JDK native2ascii 工具:

native2ascii -encoding gb2312 ApplicationResources.properties ApplicationResources_zh.properties
  • native2ascii 位於 $JAVA_HOME/bin,若提示找不到指令請檢查環境變數。
  • 產出 ApplicationResources_zh.properties 含 Unicode 編碼(如 hello.title = \u4f60\u597d\uff0c\u6b22\u8fce\u5149\u81ea\uff01)。
  • 依語系命名慣例:_zh(中文)、_en(英文)等,Struts 依 Locale 自動選取。

三、JSP 頁面使用 <bean:message> 顯示訊息

<%@ page contentType="text/html;charset=gbk"%>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

<html:html locale="true">
    <html:base/>
    <h2><bean:message key="hello.jsp.page.heading"/></h2>
    <html:errors/>
    <logic:present name="helloForm" scope="request">
        <h2>Hello <bean:write name="helloForm" property="person"/>!</h2>
    </logic:present>
    <html:form focus="person" action="helloWorld.do">
        <bean:message key="hello.jsp.prompt.person">
        <html:text property="person" maxlength="20" size="20"/><br>
        <html:submit property="submit" value="提交"/>
        <html:reset/>
    </html:form><br>
    <html:img page="/struts-power.jpg" alt="Powered by Struts"/>
</html:html>
  • 前三行引入 Struts 標籤庫,<bean:message key="hello.title"> 從資源檔讀取對應鍵值顯示。
  • <html:html locale="true"> 讓框架依瀏覽器語系自動切換資源檔。
  • 頁面編碼(charset=gbk)需與資源檔編碼一致,否則顯示亂碼。

完整流程總結

  1. 在 struts-config.xml 設定 <message-resources> 基底名稱。
  2. 建立基底 .properties 及各語系 _zh.properties、_en.properties 等。
  3. 使用 native2ascii 將非 ASCII 字元轉碼。
  4. JSP 引入 bean 標籤庫,用 <bean:message key="..."> 取值顯示。
  5. 確認頁面編碼與資源檔編碼一致。

常見坑點提醒

  • 資源檔放置位置必須在 classpath 可存取路徑(如 WEB-INF/classes/hello/)。
  • 鍵值區分大小寫,拼錯不報錯只會顯示 ???key???。
  • 若使用 UTF-8 編碼頁面,資源檔亦應以 UTF-8 存存,或統一用 native2ascii 轉碼。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved