Struts2國際化信息機制
阿新 • • 發佈:2017-07-11
spa doc ttext 發的 source dtd pro 所有 http
國際化信息機制 (三種 Action範圍、 Package範圍、 全局)
1. 全局國際化配置信息文件
全局國際化文件,對所有Action 生效,任何程序都可以訪問到,需要在struts.xml 配置常量 struts.custom.i18n.resources指定信息文件
頁面product.jsp
<span style="color: red"><s:fielderror/></span> <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
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的值
<!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頁面代碼:
<h1><s:i18n name="messages"> <s:text name="cn.wc"></s:text> </s:i18n></h1>
5. 在Action代碼獲取
在messages.properties 添加國際化信息
Action轉發的頁面JSP
<s:text name="welcome"> <s:param>lxp</s:param> </s:text>
Action代碼:
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; } }
Struts2國際化信息機制