在struts中使用國際化(i18n)
來源:互聯網
上載者:User
在struts中使用國際化(i18n) i18n可以滿足對系統的國際化,它的原理就是將頁面上的所有標誌都放到一個訊息資源檔中,不同的語言要提供不同的訊息資源檔,當使用者登入系統是,系統就是根據你登入的語言,選擇不同的訊息資源檔顯示出來,這樣你就可以看到不同的效果了。 一、設定檔的設定 其實i18n的使用還是比較簡單的,首先你要在struts-config.xml設定檔中配置訊息資源檔的路徑,如下所示:--------------------------------------------------------------------------------------------------<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"><struts-config> <!-- ========== Form Definitions =================================== --> <form-beans> <form-bean name="HelloForm" type="hello.HelloForm"/> </form-beans> <!-- ========== Global Forward Definitions?============================== --> <global-forwards> <forward name="aerror" path="/public/jsp/ShowError.jsp"/> <forward name="success" path="/public/jsp/ShowSuccess.jsp"/> </global-forwards> <!-- ========== Action Mapping Definitions ============================== --> <action-mappings> <action path="/HelloWorld" type="hello.HelloAction" name="HelloForm" scope="request"> <forward name="sayHello" path="/hello.jsp"/> </action> </action-mappings> <!-- ========== Message Resources Definitions =========================== --> <!--指定資源檔的路徑--> <message-resources parameter="hello.ApplicationResources"/>
</struts-config>------------------------------------------------------------------------------------------- 這個設定檔的配置項<message-resources>就是用來配置資源檔路徑,在這裡,路徑被配置在系統classpath裡面的hello/ApplicationResources.properties檔案中。 二、資源檔 現在我們可以開始配置資源檔了,如下(ApplicationResources.properties檔案):-------------------------------------------------------------------------------------------; Application Resources
hello.title = 你好,歡迎光臨!------------------------------------------------------------------------------------------- 在這個設定檔中,只有一個注釋(用逗號做標誌),一個資訊。對於中文來說,上面這個檔案是沒有辦法辨認的,必須給這個檔案轉化編碼才行。 在DOS命令列進入ApplicationResources.properties所在的檔案夾使用命令:native2ascii -encoding gb2312 ApplicationResources.properties ApplicationResources_zh.properties native2ascii是jdk的一個工具,放在jdk安裝目錄的bin目錄下,如果出現“native2ascii不是內部命令”,那可能是你沒有設定環境變數。
三、jsp檔案 下面是一個簡單的jsp檔案,裡面使用了i18n,如下: -------------------------------------------------------------------------------------------<%@ 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> <body> <td> <bean:message key="hello.title"/> </td> </body></html>------------------------------------------------------------------------------------------- 其中,前面三句話是將標記庫檔案包含進檔案中,這樣在下面使用的標記還可以被辨認,如下面的<bean>標記。 下面這句話<bean:message key="hello.title"/>,就是將內容顯示出來,這個內容是從檔案ApplicationResources_zh.properties讀取的,在這裡,hello.title是“你好,歡迎光臨!”,當然,這要你系統的編碼的簡體中文才行。