国际化:
准备资源文件,资源文件的命名格式如下:
baseName_language_country.properties
baseName_language.properties
baseName.properties
其中baseName是资源文件的基本名,我们可以自定义,但是language和country必须是java支持的语言和国家。如:
中国:baseName_zh_CN.properties
美国:baseName_en_US.properties
为应用添加两个资源文件
第一个存放中文:itcast_zh_CN.properties
内容为:welcome="欢迎来到北大青鸟"
第二个存入英语(美国):itcast_en_US.properties
内容为:welcome=welcome to bdqn
对于中文的属性文件,我们编写好后,应该使用jdk提供的native2ascii命令把文件转换为unicode编码的文件。
命令的使用方式如下:
native2ascii 源文件.properties 目标文件.properties
配置全局资源与输入国际化信息:
struts.custom.i18n.resources常量把资源文件定义为全局资源文件,如下:
<constant name="struts.custom.i18n.resources" value="itcast"/>
itcast为资源文件的基本名。
后面我们就可以在页面或在action中访问国际化信息:
a:在jsp页面中使用<s:text name=""/>标签输出国际化信息:
<s:text name="welcome"/>,name为资源文件中的key
b:在Action类中,可以继承ActionSupport,使用getText()方法得到国际化信息,该方法的第一个参数用于
指定资源文件中的key。
c:在表单标签中,通过key属性指定资源文件中的key,如:
<s:textfield name="realname" key="welcome"/>
两个.properties文件
welcome=welcom to bdqn
welcome=欢迎来到北大青鸟
两个struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 引用外部struts.xml文件 -->
<include file="struts_native.xml" />
</struts>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 指定默认编码集,作用于HttpServletRequest的setCharacterEncoding方法和freemarker、velocity的输入 -->
<constant name="struts.custom.i18n.resources" value="itcast" />
<package name="besa" namespace="/demo" extends="struts-default">
<action name="manage" class="cn.itcast.action.PersonManageAction" method="execute">
<result name="message">/WEB-INF/page/message.jsp</result>
</action>
</package>
</struts>
package cn.itcast.action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class PersonManageAction extends ActionSupport {
@Override
public String execute() throws Exception {
ActionContext.getContext().put("message", this.getText("welcome"));
return "message";
}
}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>国际化</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<s:text name="welcome"/>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<title>结果</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
${message }
<h1>中国万岁</h1>
</body>
</html>