這兩天學習了struts2國際化信息機制,感覺很重要,所以,今天添加一點小筆記。
國際化信息機制 (三種 action范圍、 package范圍、 全局)
1. 全局國際化配置信息文件
全局國際化文件,對所有action 生效,任何程序都可以訪問到,需要在struts.xml 配置常量 struts.custom.i18n.resources指定信息文件
頁面product.jsp
1
2
3
4
5
6
|
<s:fielderror/> <form action= "${pagecontext.request.contextpath }/product_add.action" method= "post" > 商品名:<input type= "text" name= "name" /><br/> 價格:<input type= "password" name= "price" /><br/> <input type= "submit" value= "登錄" /> </form> |
編寫productaction
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public class productaction extends actionsupport { private static final long serialversionuid = 1l; private string name; private double price; public string add(){ system.out.println(name+ "---------" +price); return success; /* get(),set()方法略去................. */ } } |
添加校驗信息:(對action的方法進行校驗 productaction-product_add-validation.xml
)
productaction-product_add-validation.xml
其中product_add
是struts.xml中action標簽中的name的值
1
2
3
4
5
6
7
8
9
10
11
|
<!doctype validators public "-//apache struts//xwork validator 1.0.3//en" "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd" > <validators> <!-- 校驗商品 --> <field name= "name" > <field-validator type= "requiredstring" > <message key= "wc" /> </field-validator> </field> </validators> |
新建國際化信息文件 src
下 messages.properties
(默認的國際化文件)
注意:
1. 其中<message key="wc"/>中的key必須是messages.properties 的key值
2.messages.properties 的value值必須裝換成unicode碼, 使用myeclipse開發工具,內置properties editor 自動將中文轉換 unicode碼
2. action范圍國際化文件
在action類 所在包 創建 action類名.properties
(無需在struts.xml 配置 )
3. package范圍國際化文件
在package下面 建立 package.properties
(無需在struts.xml )
4. 在jsp頁面獲取
在國際化 messages.properties 添加一個信息
jsp頁面代碼:
1
2
3
|
<h1><s:i18n name= "messages" > <s:text name= "cn.wc" ></s:text> </s:i18n></h1> |
5. 在action代碼獲取
在messages.properties 添加國際化信息
action轉發的頁面jsp
1
2
3
|
<s:text name= "welcome" > <s:param>lxp</s:param> </s:text> |
action代碼:
1
2
3
4
5
6
7
8
|
public class product2action extends actionsupport { private static final long serialversionuid = 1l; public string add(){ system.out.println( this .gettext( "welcome" , new string[]{ "action" })); return success; } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/lxp503238/p/7151842.html?utm_source=tuicool&utm_medium=referral