struts2教程(6)--国际化处理

来源:互联网 发布:淘宝助理5.7.8.0版本 编辑:程序博客网 时间:2024/06/06 12:39

一、Struts2国际化介绍

1、 国际化原理 

同一款软件 可以为不同用户,提供不同语言界面  ----国际化软件

需要一个语言资源包(很多properties文件,每个properties文件 针对一个国家或者语言 ,通过java程序根据来访者国家语言,自动读取不同properties文件 )



2、 资源包编写

properties文件命名 :  基本名称_语言(小写)_国家(大写).properties

例如

messages_zh_CN.properties 中国中文

messages_en_US.properties 美国英文


3ResourceBundle根据不同Locale(地域信息),读取不同国家properties文件

ResourceBundle bundle = ResourceBundle.getBundle("messages", Locale.US);


二、国际化配置

1、第一种全局国际化信息文件 (所有Action都可以使用 )

 properties文件可以在任何包中

需要在struts.xml中配置全局信息文件位置

struts.xml

<constant name="struts.custom.i18n.resources" value="messages"></constant>   messages.properties 在src根目录<constant name="struts.custom.i18n.resources" value="com.sihai.resources.messages"></constant>   messages.properties 在com.sihai.resources 包


 

国际化信息

Action中使用  :this.getText("msg");

package com.sihai.action;import com.opensymphony.xwork2.ActionSupport;public class I18nDemo1Action extends ActionSupport {@Overridepublic String execute() throws Exception {// 得到properties文件中信息.//System.out.println(this.getText("msg"));//动态文本System.out.println(this.getText("msg", new String[]{"tom"}));return NONE;}}



jsp中使用  :<s:text name="msg" />


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@taglib prefix="s" uri="/struts-tags"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>My JSP 'index.jsp' starting page</title></head><body><%--  <s:i18n name="com.sihai.action.package">  <s:text name="nameerror"/>  </s:i18n>    --%><%--<s:text name="name" />--%><s:i18n name="com.sihai.action.I18nDemo1Action"><s:text name="msg"><s:param>张三</s:param></s:text></s:i18n></body></html>


在配置文件中(校验xml) :<message key="agemsg"></message>


2、第二种 Action范围信息文件 (只能在某个Action中使用 )

数据只能在对应Action中使用,在Action类所在包 创建Action类名.properties  ---------无需配置

 3、第三种 package范围信息文件 package中所有Action都可以使用 )

数据对包 (包括子包)中的所有Action都有效 , 在包中创建package.properties -----无需配置

 4、第四种临时信息文件 (主要在jsp中 引入国际化信息 )

jsp指定读取 哪个properties文件

<s:i18n name="com.sihai.struts2.demo7.package"><s:text name="customer"></s:text></s:i18n>



 向信息中传递参数  {0} {1} ------------ MessageFormat动态消息文本

this.getText("required", new String[] { "用户名" });

 

0 1
原创粉丝点击