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

struts2国际化问题实例解析

2013-07-15 10:08 330 查看
首先国际化是解决页面的语言显示问题的,比如说外国人看网页我就让他显示英文,或者其他语言,中国人我就让他显示中文。当然这些的前提的是你本地拥有他们的语言库。

 

下面写一个全局的国际化实例

首先得配置一个properties文件。命名规则:

自定义名_语言_国家.Properties

那我起一个:my_zh_CN.properties意思就是说:有个叫my的文件使用中文中国,其实大家对_zh_CN一点不陌生。你打开浏览器的时候,点开internet选项,选择“语言”你就可以看到你的语言环境。

 

 

现在我开始做一个实例

首先说明一下:struts2 2.3版本不能用这个例子。因为自己试过,我用的struts2 .1.8

写一个my_zh_CN.properties

里面写上:

fish2={0}\uFF0C\u4F60\u597D                    // fish2是一个键,后面这是一个{0}占位符,\uFF0C\u4F60\u597D是中文“你好”的意思,只不过转化成了unicode码了。

 
我们写一个英文的

my_en_US.properties  美式英语环境

fish2={0}\uFF0Chello   两个文件的key要一样才行,

 

接着我们在struts.XML

<constant
name="struts.custom.i18n.resources"value="my"/>//加载全局资源文件,value是从properties文件中自定义名字那部分取的
   <package
name="fish"namespace="/test"
extends="struts-default">
   <action
name="redfish"class="com.fish.Test"
method="execute"
>
<result
name="success">/index.jsp</result>  

   </action>
   </package>

 

 

接着写一个关于action的java文件

Test.Java

 

packagecom.fish;
 
importcom.opensymphony.xwork2.ActionContext;
importcom.opensymphony.xwork2.ActionSupport;//必需继承这个类要不后面没有gettext方法
 
public
class
Test extends ActionSupport {
    public String execute() {
        ActionContext.getContext().put("message",
this.getText("fish2",new String[]{"不好"}));//我们把国际化的东西封装到一个request里面,this.getText("fish2",newString[]{"不好"}));fish2是一个键,但是有占位符,占位符的意思是以前没想好定义那个字符,等到要用了在往里面填字,在action里面是这样对占位符给数值的。New
string[]{}
 
        return
"success";
    }
}
下面我们写一个jsp文件

<%@
page language="java"
import="java.util.*"pageEncoding="utf-8"%>
<%@taglib
uri="/struts-tags" 
prefix="s"%>
<%
Stringpath = request.getContextPath();
StringbasePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPE
HTML PUBLIC
"-//W3C//DTDHTML 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">
    <!--
    <link rel="stylesheet"type="text/css"
href="styles.css">
    -->
  </head>
 
  <body>
  <s:text
name="fish2">//通过struts标签对国际化处理。
 <s:param>你好</s:param>//这个是对占位符的处理
  </s:text>
  ${message}//这个是利用action对国际化处理的读取值
  </body>
</html>
当我们输入

http://127.0.0.1:8080/struts2test11/test/redfish

会显示:

你好,你好 不好 你好

当我们在浏览器里面换个环境我们就会显示:

你好,hello 不好,hello

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: