the5fire

关注Python、Django、Vim、Linux、Web开发、团队管理和互联网--Life is short, we need Python.


Struts2使用I18N让软件国际化

作者:the5fire | 标签:       | 发布:2011-01-14 9:42 p.m. | 阅读量: 9416, 9129

首先需要建立login_zh_CN.properties,和login_en_US.properties两个文件,建立完成之后打开,MyEclipse以设计器方式打开,可进行可视化的编辑,这里不要使用source形式编写,因为直接在source中写中文是不识别的。在可视化编辑器中写完之后以source的形式查看,发现填写的中文会自动转换成ACSII编码。

http://img208.poco.cn/mypoco/myphoto/20110114/21/5591354820110114213006046.jpg

同样在en_US文件中设定值和名称。

然后配置Struts.xml文件,在其中需要添加:

<constant name="struts.custom.i18n.resources" value="login"></constant>

这一项,最后Struts.xml的文件配置如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
    "http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>

    <constant name="struts.devMode" value="true"></constant>
    <constant name="struts.custom.i18n.resources" value="login"></constant>
    <package name="front" namespace="/" extends="struts-default">

        <action name="login" class="com.action.LoginAction" method="login">
            <result>/login.jsp</result>
        </action>

    </package>
</struts>

建立LoginAction.java文件,里面只需要添加一个login方法,返回值为字符串“success”。 然后建立login.jsp页面;

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
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 'login.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:property value="getText('login.name')"/>
    <br/>
    <a href="login?request_locale=zh_CN">中文入口</a>
     <a href="login?request_locale=en_US">English</a>
  </body>
</html>

其实这个代码里面的request_locale=zh_CN一般都是由浏览器默认指定为本地的,不过可是进行手动设置,这里使用代码设置。

最后的资源结构如下,画箭头的是需要配置的。

http://img208.poco.cn/mypoco/myphoto/20110114/21/5591354820110114213109064.jpg

最后运行login.jsp页面,点击中文和英文即可完成对文字的转换。

我个人感觉其中的原理就是配置xml文件,然后通过struts2的来监听浏览器的语言选项读取指定的properties文件。

- from the5fire.com
----EOF-----

微信公众号:Python程序员杂谈


其他分类: