(注:对于中文的属性文件,我们编写好后,应该使用jdk提供的native2ascii命令把文件转换为unicode编码的文件。
命令的使用方式例如以下:
native2ascii 源文件.properties 目标文件.properties
可是眼下的编译器都支持直接编辑了)
当准备好资源文件之后,我们能够在struts.xml中通过struts.custom.i18n.resources常量把资源文件定义为全局资源文件,例如以下:
<constant name="struts.custom.i18n.resources" value="lc" />配置文件例如以下:
<?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>
<!-- 定义所有范围的资源文件 value是 资源文件的基本名 -->
<constant name="struts.custom.i18n.resources" value="lc" />
<package name="person" namespace="/person" extends="struts-default">
<action name="manage" class="cn.lc.action.PersonManageAction">
<result name="message">/WEB-INF/page/message.jsp</result>
</action>
</package>
</struts>
1.在JSP页面中使用<s:text name=“”/>标签输出国际化信息:
<s:text name=“welcome”/>。name为资源文件里的key
<body>
<s:text name="welcome" />
</body> 2.在Action类中,能够继承ActionSupport。使用getText()方法得到国际化信息。该方法的第一个參数用于指定资源文件里的key。public class PersonManageAction extends ActionSupport {
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
ActionContext.getContext().put("message", this.getText("welcome")); //存放在request域中
return "message";
}
}
message视图代码:
<body>
${message }
</body>
当资源文件里含有占位符时
1.在jsp页面中输出带占位符的国际化信息
<s:text name="welcome"> <s:param><s:property value="realname"/></s:param> <s:param>学习</s:param> </s:text>2.在Action类中获取带占位符的国际化信息。能够使用getText(String key, String[] args)或getText(String aTextName, List args)方法。
public class PersonManageAction extends ActionSupport {
@Override
public String execute() throws Exception {
ActionContext.getContext().put("message", this.getText("welcome",new String[]{"liming","study"})); //填充占位符
return "message";
}
}
3.用法是一样的 知识系统查找的顺序不同。
假设还没有找到相应的key。最后会从常量struts.custom.i18n.resources指定的资源文件里寻找。
<s:i18n name="lc"> <!-- lc为类路径下资源文件的基本名。 -->
<s:text name=“welcome”/>
</s:i18n> 3.假设要訪问的资源文件在类路径的某个包下。能够这样訪问:<s:i18n name=“cn/lc/action/package"> <span style="white-space: pre;"> </span><s:text name="welcome"> <span style="white-space: pre;"> </span><s:param>小张</s:param> <span style="white-space: pre;"> </span></s:text> </s:i18n>上面訪问cn.lc.action包下基本名为package的资源文件 也能够是PersonManageAction 博鳌是訪问的是该Action的PersonManageAction下边的资源文件。
原文:http://www.cnblogs.com/yangykaifa/p/7057676.html