web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>struts2</display-name>
<display-name>struts2.0</display-name>
<welcome-file-list>
<welcome-file>/web/chgLanguage/chgLang.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2.0</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2.0</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
struts.xml
<?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="struts2.0" extends="struts-default">
<action name="chgLang" class="com.chgLanguage.action.ChgLangAction">
<result name="success">/web/chgLanguage/chgLang.jsp</result>
</action>
</package>
</struts>
chgLang.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<s:a href="/struts2/chgLang.action?lang=en">English</s:a>
<s:a href="/struts2/chgLang.action?lang=zh">中文</s:a>
<h2><s:text name="name"/></h2>
<h2><s:property value="%{getText('name')}"/></h2>
</body>
</html>
package com.chgLanguage.action;
import java.util.Locale;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class ChgLangAction extends ActionSupport {
private String lang;
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
@Override
public String execute() throws Exception {
changeLang();
return SUCCESS;
}
/**
* 手动改变Locale
*/
private void changeLang() {
Locale currentLocale = Locale.getDefault();
System.out.println("===currentLocale==="+currentLocale);
System.out.println("===lang==="+lang);
System.out.println("===getLang()==="+getLang());
//1、根据页面请求,创建不同的Locale对象
if("en".equals(getLang().trim())) {
currentLocale = new Locale("en","US");
}else if("zh".equals(getLang().trim())) {
currentLocale = new Locale("zh","CN");
}
/*
* 2、设置Action中的Locale
* 前台页面的Locale和后台session中的Locale范围是不一样的
* a)只改页面Locale当前页面信息会改变但提交后Locale又会改回到默认的
* b)改变了后台Locale,当前线程中的页面Locale并不会改变,但会随下一次提交
* Action一同改变,所以可能要刷新页面两次,第一次只变后台Locale,第二次
* 前台和后台同时改变
*
* 为避免上述情况,需要前台和后台的Locale一起改变
*/
ActionContext.getContext().setLocale(currentLocale);
ServletActionContext.getRequest().getSession().setAttribute("WW_TRANS_I18N_LOCALE", currentLocale);
}
}