`

Struts2(14):Struts2的国际化

阅读更多

先看看JAVA的国际化实现:JAVA国际化是使用java.util.Locale类。

举例

1,先在SRC目录下新建两个资源文件,hellofile_en_US.properties和hellofile_zh_CN.properties

资源文件的命名格式:其中en和zh是语言名,US和CN是国家名。

hellofile_en_US.properties

hello = hello world:{0}

hellofile_zh_CN.properties

hello = \u4f60\u597d:{0}

 

测试类

package com.i18n;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

public class Test2 {
	public static void main(String[] args) {
//		Locale locale = Locale.getDefault();
		Locale locale = Locale.US;
		ResourceBundle bundle = ResourceBundle.getBundle("hellofile",locale);
		String value = bundle.getString("hello");
		String result = MessageFormat.format(value, new Object[]{"北京"});
		System.out.println(result);
	}
}

Locale.getDefault();取出的当前JVM默认的国家,如果是中国,上例将会打印出“你好:北京”


再来看看JSP页面的国际化,使用之前开发的register2.jsp,加了一个标题addUser,如果是英文:显示 Add User Information,中文 则显示:请新增用户信息

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>
  <body>
  	<table>
  		<center>
  			<s:text name="addUser"></s:text>
  		</center>
  		<s:fielderror/>
  		<s:form action ="register2">
	  		<s:textfield name="username" label="username"></s:textfield>
	  		<s:password name="password" label="password"></s:password>
	  		<s:password name="repassword" label="repassword"></s:password>
	  		<s:textfield name="age" label="age"></s:textfield>
	  		<s:textfield name="birthday" label="birthday"></s:textfield>
	  		<s:textfield name="graduation" label="graduation"></s:textfield>
	  		<s:submit value="submit"></s:submit>
  		</s:form>
  	</table>
  </body>
</html>

 

在struts.xml文件中定义资源文件名

<constant name="struts.custom.i18n.resources" value="message">

message_zh_CN.properties

addUser = \u65b0\u589e\u7528\u6237\u4fe1\u606f

 message_en_US.properties

addUser = Add User Information

 这样就实现了简单的JSP页面的国际化   

关于修改浏览器的默认语言:工具->Internet选项->常规->语言:可以添加语言,排第一的就是默认语言

注:如要实现表单的国际化:需将theme="simple"去掉。在表单标签中加上key="xxx",如下

<s:textfield name="age" key="username.invalid"></s:textfield>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics