今天做项目负责i18n国际化,索性总结一下,以下部分来自网络,已注明出处
一、 Java 国际化
1. 步骤:
1) 定义国际化资源文件
2) 根据软件的语言环境取得对应的资源文件
3) 根据key取得对应的资源文件的对应字段的value值
2. 知识内容
1) Java程序的国际化主要通过如下3个类完成
Java.util.ResourceBundle:用于加载资源包 Java.util.Locale:对应一个特定的国家/地区、语言环境 Java.text.MessageFormat:用于将消息格式化
2) 资源文件的命名可以是如下3种形式:
baseName_language_country.properties
baseName_language.properties
baseName.properties
其中baseName是资源文件的基本名称,用户可以自由定义,而language和country都不可随意变化,必须是Java所支持的语言和国家。
3. 示例
《1》首先编写两个资源文件,例如:
resource_zh_CN.properties: title=标题
resource_en_US.properties:title=title
《2》中文的可以使用jdk的native2ascii 命令进行转码Unicode编码。
命令: native2ascii resource_zh_CN..properties teme.properties然后在将转好的编码拷贝替换到resource_zh_CN.properties,替换后是:title=\u6807\u9898
package com.ascent.i18n.test;
import java.util.*;
public class ResourceBundleTest {
public static void main(String[] args) {
//设置本地区语言(默认)
Locale locale = Locale.getDefault();
//可以使用Local的常量设置具体的语言环境
//Locale locale = Locale.US;
//根据地区不同加载不同的资源文件
ResourceBundle rb = ResourceBundle.getBundle("resource", locale);
//根据key获得value值
String title = rb.getString("title");
System.out.println(title);
}
}
《3》Java国际化包含占位符的消息
以上在资源文件配置的消息都是简单的消息,假如消息中含有参数,即有参数占位,我们
如何实现呢?例如下面消息:
英文:hello=Hello,{0}!Today is {1}.
中文:hello=你好,{0}!今天是{1}.
此时,我们需要使用MessageFormat类,该类有个很有用的静态的方法
format(String pattern,value1,value2…)
返回后面多个参数值填充前面pattern字符串,其中pattern字符串就是一个带占位符的字符串。Value1代表第一个占位符的实际值,value2代表第二个占位符的值…
package com.ascent.i18n.test;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
import java.text.*;
public class MessageFormatTest {
public static void main(String[] args) {
Locale locale = Locale.getDefault();
ResourceBundle rb = ResourceBundle.getBundle("resource", locale);
String hello = rb.getString("hello");
String result = MessageFormat.format(hello, "焦学理",new Date());
System.out.println(result);
}
}
二、 struts2封装国际化
Struts 2国际化是建立在Java国际化的基础之上,一样也是通过提供不同国家/语言环境的消息资源,然后通过ResourceBundle加载指定Locale对应的资源文件,再取得该资源文件中指定key对应的消息—整个过程与Java程序的国际化完全相同,只是Struts2框架对Java程序国际化进行了进一步封装,从而简化了应用程序的国际化。
1)定义国际化资源文件
2)在struts2.xml中配置常量
3)在页面中通过struts标签获取资源文件里的值
1) 定义国际化资源文件的格式
有两种定义格式:
- global_en.properties、global_zh.properties定义于全局,放在src目录下。
- package_en.properties、package_zh.properties定义于某个包下,可以定义多组位于不同的包下。
2) 在struts2.xml中配置常量
<constant name="struts.custom.i18n.resources" value="package" />
<constant name="struts.custom.i18n.resources" value="global" />
即启用全局和所有包下的i18n的资源文件。两者之间不冲突。
3) 在页面中设置local变量
往往在登陆页面给用户选择一个语言环境。
<a href="<%=basePath%>?local=zh_CN">中文</a>
<a href="<%=basePath%>?local=en_US">英文</a>
由于struts2的封装,在拦截器栈中有i18n的设置,当发现链接中存在local=x,则将x保存在session中作为local变量的值。所以在登陆页面选择一个语言环境后,所有的页面就会自动选择对应的语言配置文件。不会出现后面的页面和前面的页面的语言环境不统一的情况。
4) 取值使用
a) JSP页面中通过标签输出国际化消息
启用struts标签:<%@ taglib uri="/struts-tags" prefix="s"%>
<s:text name="xx"/>
xx为properties文件里的key。<s:label name="xx"/>
- 表单元素的name作为提交时的字段名称被使用了,所以要使用key属性:
<s:form action="Login" method="post">
<s:textfield name="username" key="xx"/>
<s:password name="password" key="xx"/>
<s:submit name="submit" key="xx" />
</s:form>
4.<s:property value="getText('xx')"/>
5. 指定properties文件
<s:i18n name="x">
<s:text name="xx"></s:text>
</s:i18n>
b)在Action类中使用国际化消息
使用ActionSupport类的getText方法,该方法可以接受一个name 参数,该参数指定了国际化资源文件中的key
public class LoginAction extends ActionSupport{
public String execute(){
if(getUsername().equals("ascent")&& getPassword().equals("ascent")){
ActionContext.getContext().getSession().put("user", this.getUsername());
return SUCCESS;
}
return ERROR;
}
//完成输入校验需要重写的validate方法(读取资源文件getText(String str))
public void validate(){
//调用getText方法取出国际化信息
if(getUsername()==null||"".equals(this.getUsername().trim())){
this.addFieldError("username", this.getText("username.required"));
}
if(this.getPassword()==null||"".equals(this.getPassword().trim())){
this.addFieldError("password", this.getText("password.required"));
}
}
}
c) 参数化国际化字符串 (带有占位符)
许多情况下,我们都需要在运行时(runtime)为国际化字符插入一些参数,例如在输入验证提示信息的时候。在Struts 2.0中,我们通过可以方便地做到这点。
测试:
带占位符的国际化信息
welcomeTip=欢迎,{0},您已经登陆成功!
《1》.如果需要在JSP页面中填充国际化消息里的占位符,则可以通过在
<!--使用s:text标签输出welcomeTip对应的国际化信息-->
<s:text name="welcomeTip">
<!--使用s:param为国际化信息的占位符传入参数-->
<s:param><s:property value="username"/></s:param>
</s:text>
《2》.如果需要在Action中填充国际化消息里的占位符,则可以通过在调用getText方法时使用getText(String aTextName,List args)或getText(String key, String[] args)方法来填充
占位符。该方法的第二个参数既可以是一个字符串数组,也可以是字符串组成的List对象,从而完成对占位符,字符串数组、字符串集合中第二个元素将填充第二个占位符,依此类推。
public String execute(){
if(getUsername().equals("ascent")&& getPassword().equals("ascent")){
//调用getText方法取出国际化信息,使用字符串数组传入占位符的参数值(request范围)
ActionContext.getContext().put("user",this.getText("welcomeTip",new String[]{this.getUsername()}));
return SUCCESS;
}
return ERROR;
}
附:中英文切换 测试项目代码
Action
package com.lxitedu.ant;
1. import com.opensymphony.xwork2.ActionSupport;
2. import com.opensymphony.xwork2.ModelDriven;
3.
4. public class Action extends ActionSupport implements ModelDriven<User> {
5. private static final long serialVersionUID = 1L;
6. private User user = new User();
7.
8. @Override
9. public String execute() throws Exception {
10. return SUCCESS;
11. }
12.
13. @Override
14. public User getModel() {
15. return user;
16. }
17.
18. public String run() throws Exception {
19. System.out.println("Action.run()");
20. return INPUT;
21. }
22. }
user.java
package com.lxitedu.ant;
1.
2. public class User {
3. private String name;
4. private String password;
5. public String getName() {
6. return name;
7. }
8. public void setName(String name) {
9. this.name = name;
10. }
11. public String getPassword() {
12. return password;
13. }
14. public void setPassword(String password) {
15. this.password = password;
16. }
17.
18. }
资源文件
messageResource_en_US.properties
2.
3. login=login
4. password=password
5. sub=submit
6. cn=Chinese
7. us= English
8.
9. messageResource_zh_CN.properties
10.
11. login=帐号
12. password=密码
13. sub=提交
14. cn=中文
15. us=英文
16.
struts.xml
<!DOCTYPE struts PUBLIC
2. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
3. "http://struts.apache.org/dtds/struts-2.0.dtd">
4. <struts>
5. <package name="hello" namespace="/abc" extends="struts-default">
6.
7.
8. <action name="user" class="com.lxitedu.ant.Action">
9. <result name="success">/success.jsp</result>
10. <result name="input">/index.jsp</result>
11. </action>
12.
13.
14. <action name="input" class="com.lxitedu.ant.Action" method="run">
15. <result name="input">/index.jsp</result>
16. <interceptor-ref name="i18n" />
17. </action>
18.
19. </package>
20.
21. </struts>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
2. pageEncoding="UTF-8"%>
3. <%@ taglib prefix="s" uri="/struts-tags" %>
4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5. <html>
6. <head>
7. <title>Insert title here</title>
8. </head>
9. <body>
10. <a href="abc/input.action?request_locale=zh_CN"><s:label key="cn"/></a><br/>
11. <a href="abc/input.action?request_locale=en_US"><s:label key="us"/></a>
12.
13.
14. <s:form action="abc/user.action">
15. <s:textfield name="name" key="login" /><br/>
16. <s:textfield name="password" key="password" /><br/>
17. <s:submit key="sub"/>
18. </s:form>
19. </body>
20. </html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
2. pageEncoding="UTF-8"%>
3. <%@ taglib prefix="s" uri="/struts-tags" %>
4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5. <html>
6. <head>
7. <title>Insert title here</title>
8. </head>
9. <body>
10.
11. user Name: <s:property value="name" /><br/>
12. password: <s:property value="password"/>
13.
14. </body>
15. </html>
以上参照 http://blog.csdn.net/sd0902/article/details/8393182。
三、 jQuery实现国际化
jQuery.i18n.properties 是一款轻量级的 jQuery 国际化插件。与 Java 里的资源文件类似,jQuery.i18n.properties 采用 .properties 文件对 JavaScript 进行国际化。
jQuery.i18n.properties API
jQuery.i18n.properties 的 API 非常简单,只有少数几个 API,即 jQuery.i18n.properties()、jQuery.i18n.prop()、jQuery.i18n.browserLang()。当然,和其他 jQuery 插件一样,我们也可以采用 .i18n.properties()、 .i18n.prop() 和 $.i18n.browserLang() 的形式使用这用这些 API。
1. jQuery.i18n.properties(settings)
该方法加载资源文件,其中 settings 是配置加载选项的一系列键值对,各配置项的具体描述请查阅下面贴出的网址。
示例:
jQuery.i18n.properties({
name:'strings',// 资源文件名称
path:'bundle/',// 资源文件所在目录路径
mode:'both',// 模式:变量或 Map
language:'pt_PT',// 对应的语言
cache:false,
encoding: 'UTF-8',
callback: function() {// 回调方法
}
});
2. jQuery.i18n.prop(key)
该方法以 map 的方式使用资源文件中的值,其中 key 指的是资源文件中的 key。当 key 指定的值含有占位符时,可以使用 jQuery.i18n.prop(key,var1,var2 … ) 的形式,其中 var1,var2 …对各占位符依次进行替换。例如资源文件中有“msg_hello= 您好 {0},今天是 {1}。”的键值对,则我们可以采用“jQuery.i18n.prop( ‘ msg_hello ’ , ’小明’ , ’星期一’ );”的形式使用 msg_hello。
3. jQuery.i18n.browserLang()
用于获取浏览浏览器的语言信息,这里不再单独介绍。
详细使用示例请访问:http://www.ibm.com/developerworks/cn/web/1305_hezj_jqueryi18n/。