首页 > 编程 > Java > 正文

深入理解Struts2国际化信息机制

2019-11-26 11:52:35
字体:
来源:转载
供稿:网友

这两天学习了Struts2国际化信息机制,感觉很重要,所以,今天添加一点小笔记。

国际化信息机制  (三种 Action范围、 Package范围、 全局)

1. 全局国际化配置信息文件

全局国际化文件,对所有Action 生效,任何程序都可以访问到,需要在struts.xml 配置常量 struts.custom.i18n.resources指定信息文件

页面product.jsp

<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

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;      }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表