1.搭建struts2框架的流程,请看第一条博客。
2.国际化简称i18n,其来源是英文单词 internationalization的首末字符i 和n。18为中间的字符数。
国际化文件的命名规则:
1、基本名.properties 如:message.properties
2、基本名_语言编码_国家编码.properties 如:message_zh_CN.properties, message_en_US.properties 其中语言编码和国家编码是固定的,可以在JDK中Locale类的常量中找到。
Java中已经实现了国际化功能,struts2中只是对该功能进行了整合,以方便我们的使用。
Struts2中使用到国际化的地方有: 1、jsp页面的国际化; 2、Action信息国际化; 3、转换错误信息的国际化; 4、校验错误信息的国际化;
Struts2国际化文件分类: 1、全局范围国际化文件 2、包范围国际化文件 3、Action类范围国际化文件。
全局范围国际化文件:
编写一个messages_zh_CN.properties和messages_en_US.properties放在src下。
在这里插入图片描述
3.创建视图层,即idex.jsp页面
<!-- 局部定义使用哪一种国际化语音 -->
<s:i18n name="messages">
<a href="check.action?request_locale=zh_CN"><s:text name="chinese"></s:text></a>
<a href="check.action?request_locale=en_US"><s:text name="english"></s:text></a>
<form action="<%=basePath%>login.action" method="post">
<table>
<tr>
<td><s:text name="login.username"/></td>
<td><input type="text" name="user.userName"/></td>
</tr>
<tr>
<td><s:text name="login.password"/></td>
<td><input type="text" name="user.password"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="<s:text name="login.btn"/>"/></td>
</tr>
</table>
</form>
</s:i18n>
还有登录成功页面,即:show.jsp
4.在com.hnpi.action包下,创建类,一个RegisterActio类,
为了获取index.jsp的属性值,还有返回success
package com.hnpi.action;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction{
private String name;
private String pwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String t1(){
return "success";
}
}
另一个ChangeLanguageAction类,目的是返回success
package com.hnpi.action;
public class ChangeLanguageAction {
public String execute(){
return "success";
}
}
5.配置修改struts.xml,即:
<?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.custom.i18n.resources" value="messages" />
<package name="default" extends="struts-default">
<action name="check" class="com.hnpi.action.ChangeLanguageAction">
<result name="success">/index.jsp</result>
</action>
<action name="login" class="com.hnpi.action.RegisterAction"
method="t1">
<result name="success">/show.jsp</result>
</action>
</package>
</struts>
最后实现中英文的转换,实现效果如下: