[Strtus2]国际化 中英切换
国际化 中英切换例子:
- 首先我们得确保strtus框架搭建完毕
- 在src下创建massages_en_US.properties和massages_zh_CN.properties
massages_en_US.properties:
login.username=userName
login.password=passWord
login.btn=login
chinese=chinese
english=english
check=please your language
massages_zh_CN.properties:
login.username=\u767B\u5F55\u7528\u6237\u540D
login.password=\u767B\u5F55\u5BC6\u7801
login.btn=\u767B\u5F55
chinese=\u4E2D\u6587
english=\u82F1\u6587
check=\u8BF7\u9009\u62E9\u8BED\u8A00
文件会自动把中文汉字转换为unicode编码格式如下:
- 在com.hnpi.action下新建ChangeLanguage.java类:(什么都不做,只是返回success)
package com.hnpi.action;
public class ChangeLanguageAction {
public String execute(){
return "success";
}
}
- 然后我们来配置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>
- 视图页面:index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
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="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>
</body>
</html>
这里有一个i18n,他就是Internationalization(国际化)的英文缩写,为什么是i18n呢?
Internationalization去掉头尾的i和n刚好还剩下18个字符。
在struts2中,提供了一个i18n的拦截器,这个拦截器在执行Action方法之前,自动查找请求中名为request_locale的参数,拦截后转换为Locale对象,放置在用户session的名为“WW_TRANS_i18N_LOCALE”的属性。i18n在程序运行时会被自动加载,我们可以利用这些来设置允许用户自动选择网页的语言。
效果图如下: