Struts2 关于i18n国际化的问题,可点击链接实现中英文切换
1.首先把Struts2的环境搭建起来,
?
2.建立一个action.测试i18n的。
?
3.下面这个是struts.xml的简单配置,里有2中properties文件的配置,一种是全局的,一种是局部的,
<?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> <constant name="struts.devMode" value="true" /><!-- 局部的配置 --><!--<constant name="struts.custom.i18n.resources" value="com/test/action/I18n"></constant> --><!-- 全局的配置 --><!-- --><constant name="struts.custom.i18n.resources" value="test"></constant> <package name="default" namespace="/" extends="struts-default"><action name="" name="code"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"> </head> <body> <a href="<%=basePath%>?local=zh_CN">中文</a> <a href="<%=basePath%>?local=en_US">英文</a> This is my JSP page. <br> <s:debug></s:debug> property:<s:property value="getText('hello')"/><br> text:<s:text name="hello"></s:text><br> i18n:<s:i18n name="test"> <s:text name="hello"></s:text> </s:i18n> </body></html>?
?
6.想要实现中英文切换,还要在action中加入这一一句话
Locale locale=new Locale("zh","CN");//(这个能根据你传来的值动态改变)ServletActionContext.getRequest().getSession().setAttribute("WW_TRANS_I18N_LOCALE", locale);?
7.基本上可以实现动态链接切换中英文了,不过,还有个小问题,需要解决,那就是,需要点击2下中文才能切换到中文,
英文同样也是,这个问题怎么解决呢?
?
8.想解决那个问题其实很简单,配置一个fitler拦截器就行了,这个拦截器最好配置在struts2的拦截器前面,
拦截器的内容大概是:
String local=arg0.getParameter("local");if(local!=null){String loc[]=local.split("_");Locale locale=new Locale(loc[0],loc[1]);((HttpServletRequest)arg0).getSession().setAttribute("WW_TRANS_I18N_LOCALE", locale);}arg2.doFilter(arg0, arg1);???这样就能实现动态切换中英文了。