struts2的国际化(实例)【实现网站可以中英等多语言切换】
使用struts.custom.i18n.resources常量实现国际化
网站实现国际化,需要为其提供国际化的资源文件(就是各种语言包)。
资源文件基本内容是key=value形式;其中key为程序使用部分,也就是关键词,value为对应的值。 资源文件中的值为ASCII格式【可以参考下方实例中的中文资源文件】
例如:login_username=username
使用:在使用时,在对应的位置写上key,网站运行后就会自动从资源文件中选区key对应的值并显示。
资源文件的一般有三种:
- MyName_zh_CN.properties 表示使用中文,并且地区为中国
- MyName_zh.properties 表示使用中文,地区不限制
- MyName.peoperties 表示默认的资源文件,如果没有指定地区,但是切换为该地区,找不到资源文件时,就使用该资源文件。
MyName是基名,这个为自己设置。zh表示中文(如果为en则表示为英文);CN表示中国(如果为US则表示美国)
英语资源文件举例:
- MyName_en_US.properties 表示使用英语,并且地区在美国
- MyName_en.properties 表示使用英语,地区不限制
具体语言、地区代码请参考网站:
https://www.iso.org/obp/ui/#search
接下来是一个实例:
项目目录:
资源文件:
MyResources_en_US.properties
MyResources_zh.properties【注意这里的中文应该为ASCII编码| 在Eclipse中,当你打上中文时,会自动为你转换为ASCII编码】
MyResources.properties
编写测试用的jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:a href="login?request_locale=zh_CN" ><s:text name="login_chinese"></s:text></s:a>
<s:a href="login?request_locale=en_US" ><s:text name="login_english"></s:text></s:a>
<s:a href="login?request_locale=jp" ><s:text name="login_other"></s:text></s:a>
<hr>
<s:form action="login" >
<s:textfield name="username" key="login_username" />
<br />
<s:password name="password" key="login_password" />
<br />
<s:submit type="button" key="login_loginButton"></s:submit>
</s:form>
<hr>
</body>
</html>
Action
package action;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.SessionAware;
public class userAction extends ActionSupport {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String Login() {
return SUCCESS;
}
}
struts.xml页面
在配置文件中使用struts.custom.i18n.resources常量配置资源文件的基名(MyResources),这个名字可以自己设置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="login" class="action.userAction" method="Login">
<result name="success">index.jsp</result>
</action>
</package>
<constant name="struts.custom.i18n.resources" value="MyResources"></constant>
</struts>
最后看运行结果
中文显示
英文显示
选择其它语言时,系统会自己去寻找对应的资源文件,如果没有就使用当前默认的语言(由于本机使用的是中文环境),既汉语显示,因此会使用MyResources_zh.properties资源文件,如果删除改资源文件后,就会访问MyResources.peoperties即默认的资源文件!
因此,如果需要添加其它的国家和语言,则只需要增加对应的资源文件即可!