關於struts標籤bean:message


bean:message標籤用來從指定的locale中取回國際化的消息並輸出,在這個過程中我們還可以傳遞五個以內的參數。message key可以通過key直接指定,也可以通過name和property間接的指定。

bean:message標籤有兩種指定message key的方式,一是通過key屬性直接指定;二是通過name和property屬性間接的指定,其中message key是在message resources文件中定義的。

我們可以在struts-config.xml文件中使用<message-resources>來設置message resources文件。

爲了介紹該標籤我使用了三個message resources文件,三個文件的名字分別爲Resources.properties、Resources_en.properties和Resources_zh.properties。在struts-config.xml文件中的設置(這裏不用設置三個,struts會依據locale自動找到對應的文件)如下:

<message-resources parameter="Resources" />
三個message resources文件中定義的message key爲:

<!-- Resources.properties -->
resource=Resources.properties.
from=Resources.properties.
<!-- Resources_en.properties -->
from=Resources_en.properties.
<!-- Resources_zh.properties
from=Resources_zh.properties.
下面的代碼片段示例了bean:message標籤的用法:

<bean:message key="from"/><br/>
<bean:message key="resource"/><br/>
<html:link action="/locale?language=en">English</html:link>
<html:link action="/locale?language=zh">Chinese</html:link>
上面的代碼中含有改變locale的兩個html:link標籤,要使它們工作您的struts-config.xml文件中必須含有下面定義的form和action:

<form-bean name="localeForm"
type="org.apache.struts.action.DynaActionForm">
<form-property name="language" type="java.lang.String" />
<form-property name="country" type="java.lang.String" />
<!--action成功後要跳到那裏-->
<form-property name="page" type="java.lang.String"
initial="/message.jsp"/>
</form-bean>

<action path="/locale" type="org.apache.struts.actions.LocaleAction"
name="localeForm" scope="request">
</action>
在不同的locale下我們得到了如下的兩個結果:

在locale爲zh時的結果:
Resources_zh.properties.
Resources.properties.
在locale爲en時的結果:
Resources_en.properties.
Resources.properties.
讓我們來看一下在locale爲zh時如何得到的是上面的結果。因爲locale爲zh所以<bean:message key="from"/><br/>先找Resources_zh.properties這個文件從中得到form鍵的值。而<bean:message key="resource"/><br/>也會先找Resources_zh.properties這個文件但這次沒有找到resource鍵,這時Struts會到Resources.properties這個文件中找,很幸運這裏找到了。如果還沒有找到,或message resource文件不存在就會拋出異常。當locale爲en時類似,可以自己試試。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章