使用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即默認的資源文件!
因此,如果需要添加其它的國家和語言,則只需要增加對應的資源文件即可!