您的位置:首页 > 编程语言 > Java开发

19、struts国际化的切换

2009-08-27 11:19 134 查看
在18、struts硬编码国际化的基础上,实现struts国际化的切换
1、了解利用struts默认将locale放到session中的特性,完成采用编程的方式切换语言设置
* 参见:ChangeLanguageAction.java
2、在index.jsp页面中增加
<a href="changelang.do?lang=zh">中文</a>
<a href="changelang.do?lang=en">英文<a/>3、ChageLanguageAction.java
Code
package com.bjsxt.struts;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class ChangeLanguageAction extends Action {

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//获得参数
String lang = request.getParameter("lang");
//得到当前的默认Locale
Locale currentLocale = Locale.getDefault();
if ("zh".equals(lang)) {
currentLocale = new Locale("zh", "CN");
}else if("en".equals(lang)) {
currentLocale = new Locale("en", "US");
}

//在Action中有setLocale方法来设置Locale
this.setLocale(request, currentLocale);
//也可以用使用如下方法
//request.getSession().setAttribute(Globals.LOCALE_KEY, currentLocale);
return mapping.findForward("index");
}

}
4、struts-config.xml加入配置信息
<action path="/changelang"
type="com.bjsxt.struts.ChangeLanguageAction"
>
<forward name="index" path="/index.jsp"/>
</action>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: