struts2之I18N

---恢复内容开始---

写两个properties文件,命名时要注意后面的中文的则以zh_CN结尾,英文的以en_US结尾。

在测试驱动类中写

ResourceBundle res = ResourceBundle.getBundle("app", Locale.CHINA);

System.out.println(res.getString("welcome.msg"));

welcome.msg为properties文件中的信息。

这里Locale用的是国家名

但是在ch_ZN里面写中文还是不行的,用properties editor打开即可,它会自动将输入的中文转为unicode字符。

properties插件:解压,feafures pligin覆盖到Myeclipse中的eclipse目录里

---恢复内容结束---

Action级别I18N问题

写好资源文件后,在jsp页面可以用s 标签取出如:<s:property value="getText('login.username')"/>

properties里面调用方法,只能针对action来调。LoginAction里面虽然没有getText方法,但是它的父类ActionSupport里面有getText方法。

包级别的I18N,前缀名只能叫package,如package_zh_CN.properties。只能它所在的包才能用

action级别的前缀名只能叫XXAction,只有它对应的action才能用。

全局级别的I18N前缀名不收限制,整个项目都可以用,为了找到它,要在struts.xml里面配置它的前缀名。怎么配参考defualt.properties

如:<constant name="struts.custom.i18n.resources" value="bbs2"/>

处理资源文件中的参数

{0}{1}{2}分代表一个占位符,里面的数字表示它们的参数位置,从0开始 如welcome.msg = welcome:{0}! 在jsp页面可以往里面传参数

<s:text name="welcome.msg">
<s:param value="username"></s:param>
</s:text>

动态语言的切换

只要在地址后面加上?request_locale=en_US就可以切换为英文,加?request_locale=zh_CN就可以切换为中文

我们可以写个LangAction

1 package com.lch.bbs2009.action;
2 
3 import com.opensymphony.xwork2.ActionSupport;
4 
5 public class LangAction extends ActionSupport {
6     public String execute(){
7         return "success";
8     }
9 }

在struts.xml中配置

  <action name="lang" class="com.lch.bbs2009.action.LangAction">
            <result name="success">/admin/Login-input.jsp</result>
        </action>

在jsp页面中添加链接

1 <a href="admin/lang?request_locale=en_US">en</a>
2     <a href="admin/lang?request_locale=zh_CN">cn</a>
原文地址:https://www.cnblogs.com/ligui989/p/3223275.html