Dashboard > OpenSource Project > ... > Spring > 入門 13 - MessageResource介面
OpenSource Project Log In   View a printable version of the current page.
入門 13 - MessageResource介面
Added by minqing, last edited by 良葛格 on Nov 19, 2004  (view change)
Labels: 
(None)

Reference by caterpillar ,caterpillar

ApplicationContext繼承了org.springframework.context.MessageResource介面,您可以使用getMessage()的各個簽署方法來取得訊息資源,從而實現國際化訊息的目的。

在這個主題中,我們簡單的透過MessageResource的一個實作org.springframework.context.support.ResourceBundleMessageSource來取得國際化訊息,首先在Bean定義檔中撰寫:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd"> 
<beans> 
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 
        <property name="basename"> 
            <value>messages</value> 
        </property> 
    </bean> 
</beans>

basename屬性用來設定訊息資源的前置檔案名稱,在這邊設定是messages,則訊息資源檔的名稱可以是messages_en_US.properties、messages_zh_TW.properties、messages_*.properties等等名稱,在這邊我們提供兩個:messages_en_US.properties、messages_zh_TW.properties,首先messages_en_US.properties內容如下:

userlogin=User {0} login at {1}

message_zh_TW.properties內容如下:

userlogin=使用者 {0} 於 {1} 登入

其中{0}與{1}是我們可以在程式執行過程中設定的參數。Spring實際上會使用JDK的ResourceBundle來讀取這些文件,而中文在編碼過程中會發生問題,為了要能正確的顯示中文,我們必須對message_zh_TW.properties進行編碼轉換,使用JDK工具中的native2ascii即可:

native2ascii message_zh_TW.properties message_zh_TW.txt

之後將message_zh_TW.txt覆蓋(替換)掉message_zh_TW.properties就可以了。

接下來撰寫一個簡單的測試程式:

package onlyfun.caterpillar; 

import java.util.*; 
import org.springframework.context.*; 
import org.springframework.context.support.*; 

public class Test { 
    public static void main(String[] args) throws Exception { 
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); 

        Object[] arguments = new Object[] {"良葛格", Calendar.getInstance().getTime()}; 

        System.out.println(context.getMessage("userlogin", arguments, Locale.US)); 
        System.out.println(context.getMessage("userlogin", arguments, Locale.TAIWAN)); 
    } 
}

ClassPathXmlApplicationContext實作了ApplicationContext介面,我們使用其來讀取Bean定義檔,並返回一個ApplicationContext介面的實例,透過設定參數並指定Locale,我們使用getMessage()設定對應的訊息,這個測試程式結果會顯示以下的內容:

log4j:WARN No appenders could be found for logger (org.springframework.beans.factory.xml.XmlBeanDefinitionReader). 
log4j:WARN Please initialize the log4j system properly. 
User 良葛格 login at 10/28/04 12:52 PM 
使用者 良葛格 於 2004/10/28 下午 12:52 登入

Site powered by a free Open Source Project / Non-profit License (more) of Confluence - the Enterprise wiki.
Learn more or evaluate Confluence for your organisation.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.1.5a Build:#411 Mar 16, 2006) - Bug/feature request - Contact Administrators