Stuts2 国际化切换
action类
import java.util.Locale;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class SwitchLanguageAction extends ActionSupport{
//这里定义两个参数
private String loc;
private String lan;
public String switchLanguage(){
//创建语言对象
Locale le=new Locale(lan,loc);
//存入会话中
ServletActionContext.getRequest().getSession().setAttribute("WW_TRANS_I18N_LOCALE", le);
//启用
ServletActionContext.getContext().setLocale(le);
return SUCCESS;
}
//get、set方法
....
}
struts.xml 中
<!-- 国际化,多语言切换 >
<constant name="struts.custom.i18n.resources" value="basename"/>
<package name="test" extends="struts-default,json-default" namespace="/">
<action name="switch_*" class="com.ym.action.SwitchLanguageAction" method="{1}">
<result name="success">/login.jsp</result>
</action>
</package>
每个语种都要有个xxxx_xx_XX.properties文件
例如我这里就只有中文和英文切换,就创建了两个properties文件
basename_en_US.properties 表示英文
name | value |
---|---|
log_pwd | password |
log_Name | Login account |
log_sub | Login |
basename_zh_CN.properties 表示中文
name | value |
---|---|
log_pwd | 密码 |
log_Name | 账号 |
log_sub | 登录 |
这里说一哈:所有的properties文件中的name要是一模一样的,value 则就是每种语言对应的相同含义
jsp页面中:
在jsp页面头文件上要引入
<%@ taglib uri="/struts-tags" prefix="s"%>
在jsp中切换输出类容为
<s:text name="log_sub" />
//这里的name中属性值要与.properties配置文件的name要一致
Eg:
<button type="submit"><s:text name="log_sub" /></button>
语言切换请求
<a href="switch_switchLanguage.action?lan=zh&loc=CN">中文</a>
<a href="switch_switchLanguage.action?lan=en&loc=US">英文</a>