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="" class="com.test.action.I18nAction">
<result >/index.jsp</result>
</action>
</package>
</struts>
4.根据struts2的配置,插件一个名字为test_en_US.properties和test_zh_CN.properties的配置文件,
test_en_US.properties里面的内容为:hello=hi,hello
test_zh_CN.properties里面的内容为:hello=\u4F60\u597D (注意了:这个是通过编码编译过来的,也可以试用MyEclipse的properties自动编辑转换实现)。
5.下面是jsp的展现页面:本人整理了以下几种实现方法,
<%@ 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);
这样就能实现动态切换中英文了。