1,下载语言切换所需要的js jquery.localize.js http://webscripts.softpedia.com/script/Modules/jQuery-Plugins/jQuery-localizationTool-js-83407.html
2,在web.xml中添加代码,拦截json格式数据,配置文件是json文件
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.json</url-pattern>
</servlet-mapping>
3,定义三个json文件,text-zh.json,text-ja.json,text-en.json(中文需要转义 防止可能出现乱码)
(1)text-en.json
{
"acc": {
"HelpCenter": "Help center",
"BusinessCenter": "Business Center",
"Exit": "[Exit]",
"BusinessSupport": "Business Support"
}
}
(2)text-zh.json
{
"acc": {
"HelpCenter": "帮助中心",
"BusinessCenter": "商家中心",
"Exit": "[退出]",
"BusinessSupport": "商家支持"
}
}
(3)text-ja.json
{
"acc": {
"HelpCenter": "ヘルプセンター",
"BusinessCenter": "商家センター",
"Exit": "[名目]",
"BusinessSupport": "企業支持"
}
}
4,语言切换 jsp页面添加
<select id="ddlSomoveLanguage" οnchange="chgLang();">
<option value="zh">选择</option>
<option value="zh">中文</option>
<option value="en">ENGLISH</option>
<option value="ja">日本語</option>
</select>
5,在需要切换的地方引入对应的方法 data-localize="acc.HelpCenter"
<a data-localize="acc.HelpCenter" href="$!webPath/articlelist_help.htm">帮助中心</a>
6,写一个language-coockies.js 文件,$("[data-localize]").localize("text", {pathPrefix: ctx+"/resources/lang", language:"en"});pathPrefix表示json文件路径的前缀,text和en对应文件名text-en.json
var name = "somoveLanguage";
/*server*/
var ctx = window.document.location.href.substring(0,window.document.location.href.indexOf(window.document.location.pathname));
function chgLang() {
var value = $("#ddlSomoveLanguage").children('option:selected').val();
SetCookie(name,value);
location.reload();
}
function SetCookie(name,value){
var Days = 30; //此 cookie 将被保存 30 天
var exp = new Date(); //new Date("December 31, 9998");
exp.setTime(exp.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function getCookie(name)//取cookies函数
{
var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
if(arr != null) return unescape(arr[2]); return null;
}
$(function() {
var uulanguage = (navigator.language || navigator.browserLanguage).toLowerCase();
if (uulanguage.indexOf("en") > -1) {
$("[data-localize]").localize("text", {pathPrefix: ctx+"/resources/lang", language: "en"});
}else if (uulanguage.indexOf("zh") > -1) {
$("[data-localize]").localize("text", {pathPrefix: ctx+"/resources/lang", language: "zh"});
}else if (uulanguage.indexOf("ja") > -1) {
$("[data-localize]").localize("text", {pathPrefix: ctx+"/resources/lang", language: "ja"});
}else{
$("[data-localize]").localize("text", {pathPrefix: ctx+"/resources/lang", language: "zh"});
};
if (getCookie(name) != "") {
if (getCookie(name) == "zh") {
$("[data-localize]").localize("text", {pathPrefix: ctx+"/resources/lang", language: "zh"});
}
if (getCookie(name) == "en") {
$("[data-localize]").localize("text", {pathPrefix: ctx+"/resources/lang", language: "en"});
}
if (getCookie(name) == "ja") {
$("[data-localize]").localize("text", {pathPrefix: ctx+"/resources/lang", language: "ja"});
}
}
});
7,