简单的一个示例,实现通过页面参数控制国际化,本示例使用struts2自带国际化支持,因此自定义国际化需要在程序中覆盖ActionContext中的Locale,即“ActionContext.setLocale(Locale.myLocale);”.
众所周知,在页面上可以通过参数“request_locale”来设置地域信息,请参考I18nInterceptor类。可是某些老系统地域信息参数并不一定就是“request_locale”,也许是另外的命名,如“locale=en_US”,这个时候就需要采取一些手段来覆盖ActionContext的Locale。下面提供了一个简单的方案,即自定义拦截器实现以编码的方式设置地域。
1,自定义拦截器
package cn.hunnu.icc.interceptor; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.Interceptor; public class ICCI18nInterceptor implements Interceptor { private static final long serialVersionUID = -6900869173567029950L; private final static Log log = LogFactory.getLog(ICCI18nInterceptor.class); @Override public void destroy() { log.info("destorying ICCI18nInterceptor.."); } @Override public void init() { log.info("initializing ICCI18nInterceptor..."); } @Override public String intercept(ActionInvocation invocation) throws Exception { System.out.println("开始设置自定义Locale..."); invocation.getInvocationContext().setLocale(Locale.UK); System.out.println("自定义Locale设置完毕!"); return invocation.invoke(); } }
2,将自定义拦截器加入到默认拦截器栈,注意,必须声明在struts默认i18n拦截器之后。
<package name="ICCardManager" namespace="/" extends="struts-default"> <interceptors> <interceptor name="iccI18nInterceptor" class="cn.hunnu.icc.interceptor.ICCI18nInterceptor"></interceptor> <interceptor-stack name="iccInterceptor"> <interceptor-ref name="defaultStack"></interceptor-ref> <interceptor-ref name="iccI18nInterceptor"></interceptor-ref> </interceptor-stack> </interceptors> <default-interceptor-ref name="iccInterceptor"></default-interceptor-ref> ... </package>
3,测试用Action
public String execute() { log.info("execute HelloAction..."); HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("userName", account); sleep(2000); System.out.println("正在执行Action..."); System.out.println("当前local:"+this.getLocale()); sleep(2000); request.setAttribute("msg", "对不起,您的输入有误,请重新输入!"); return LOGIN; }
4,输入结果
开始设置自定义Locale... 自定义Locale设置完毕! [QC] INFO [TP-Processor3] cn.hunnu.icc.action.LoginAction.execute(28) | execute HelloAction... 正在执行Action... 当前local:en_GB 正在执行Jsp...