在struts2中需要做国际化的有:
jsp页面的国际化,action错误信息的国际化,转换错误信息的国际化,校验错误信息的国际化
<constant name="struts.locale" value="zh_CN"/>
<!-- 多个文件的话用逗号隔开 -->
<constant name="struts.custom.i18n.resources" value="message"/>
中英文切换功能,只需要在请求的url后面带上参数request_locale=zh_CN或者request_locale=en_US就会被i18N拦截器拦截然后转换成中文环境。
在Struts2.3.4的文档里面是这样介绍i18n的:
1.Messages and Errors from the ValidationAware interface (implemented by ActionSupport and ValidationAwareSupport)
2.Within action classes that extend ActionSupport through the getText() method
所以要想使用国际化功能必须实现ValidationAware接口或者继承ActionSupport
Resource Bundle Search Order(资源包搜索顺序)
1.ActionClass.properties
2.Interface.properties (every interface and sub-interface)
3.BaseClass.properties (all the way to Object.properties)
4.ModelDriven's model (if implements ModelDriven), for the model object repeat from 1
5.package.properties (of the directory where class is located and every parent directory all the way to the root directory)
6.search up the i18n message key hierarchy itself
7.global resource properties
其顺序是Action类名的资源文件>>>>接口名的资源文件>>>>package.properties>>>>global.properties
资源文件名的命名包括基本名(如Action类名,message),语言代号(如en、zh),国家代号(如US、CN)组成。
例如基本名为message的简体中文资源文件就是message_zh_CN.properties
这是转码后的资源文件:
lable.titile=用户注册
lable.username=用户名
lable.pwd=密码
lable.age=年龄
lable.email=电子邮箱
lable.regbutton=注册按钮
validator.error.required={0}必须填写。
validator.error.maxlength={0}最多允许{1}个字符。
validator.error.range={0}必须介于{1}至{2}之间。
validator.error.regex={0}格式不正确。
在JSP页面中使用 s:text 标签对文本国际化:
<s:text name="lable.username"/>
<s:text name="lable.pwd"/>
<input type="submit" value='<s:text name="lable.regbutton"/>'/>
OGNL表达式读取国际化消息:
<s:set name="age" value="%{getText('lable.age')}"/>
使用带有占位符的国际化信息时:
//从资源文件中读取username.invalid的值,增加到ActionError中。
addActionError(getText('validator.error.maxlength', {'密码', '20'})));
<s:text name="validator.error.range">
<s:param>年龄</s:param>
<s:param>0</s:param>
<s:param>100</s:param>
</s:text>