package org.apache.struts.webapp.validator; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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 final class LocaleAction extends Action { private Log log = LogFactory.getFactory().getInstance(this.getClass().getName()); public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Extract attributes we will need HttpSession session = request.getSession(); Locale locale = getLocale(request); String language = null; String country = null; String page = null; try { language = (String) PropertyUtils.getSimpleProperty(form, "language"); country = (String) PropertyUtils.getSimpleProperty(form, "country"); page = (String) PropertyUtils.getSimpleProperty(form, "page"); } catch (Exception e) { log.error(e.getMessage(), e); } if ((language != null && language.length() > 0) && (country != null && country.length() > 0)) { locale = new java.util.Locale(language, country); } else if (language != null && language.length() > 0) { locale = new java.util.Locale(language, ""); } session.setAttribute(Globals.LOCALE_KEY, locale); if (null==page) return mapping.findForward("success"); else return new ActionForward(page); } }
在struts-config.xml中添加一个 动态actionFrom
<form-beans>
......
<from-bean name="Language" type="org.apache.struts.DynaActionForm">
<form-property name="language" type="String"/>
<form-property name="country" type="String"/>
</from-bean>
........//其它的formbean
</form-beans>
配置Action
<action path="ChangeLocale" name="Language" type="org.apache.struts.actions.LocaleAction">
<forward name="success" path="default.jsp" />
</action>
注意:forward的name必须为success,path为切换语言后跳转的页面.
jsp
<a href="ChangeLocale.do?language=CN&country=zh">简体中文</a>
<a href="ChangeLocale.do?language=TW&country=zh">繁体中文</a>
<a href="ChangeLocale.do?language=US&country=en">English</a>