Struts2的国际化例子
Struts2的国际化例子
要求:Struts2框架环境搭建成功
1.首先创建一个jsp页面层。
如图:
jsp页面代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
<!-- 局部定义使用哪一种国际化语音 -->
<s:i18n name="message">
<s:text name="check"></s:text>
<a href="login.action?request_locale=zh_CN"><s:text name="chinese"></s:text></a>
<a href="login.action?request_locale=en_US"><s:text name="english"></s:text></a>
<form action="<%=basePath%>hello.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.pwd"/></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>
</body>
</html>
.这里有一个i18n,他就是Internationalization(国际化)的英文缩写,
Internationalization去掉头尾的i和n刚好还剩下18个字符。
2.下面要在src下资源包file中创建两个资源文件:
中文
英文
3.需要再新建两个Action
3.1:
我们要注意创建时要继承ActionSupport如下:
这个Action的代码如下:
package com.hnpi.action;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport {
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 a1(){
System.out.println(this.getText("login.username"));
return"success";
}
}
3.2第二个Action创建如下:
代码如下:
package com.hnpi.action;
public class ChangLanguageAction {
public String execute(){
return"success";
}
}
4.在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="message"/>
<package extends="struts-default" namespace="/" name="default">
<action name="check" class="com.hnpi.action.ChangLanguageAction" >
<result name="success">/demo.jsp</result>
</action>
<action name="hello" method="a1" class="com.hnpi.action.RegisterAction" >
<result name="success">/welcome.jsp</result>
</action>
</package>
</struts>
最后看看运行结果