08-struts2的国际化

Struts2国际化

1、 国际化原理 ? 什么是国际化 ?

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

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

      

2、 资源包编写

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

例如 :

       messages_zh_CN.properties 中国中文

       messages_en_US.properties 美国英文

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

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

4.struts2中国际化

struts2中对国际化进行了封装,我们只需要根据其提供的API进行访问就可以。

第一种 全局国际化信息文件 (所有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="cn.itcast.resources.messages"></constant>   messages.properties 在 cn.itcast.resources 包

国际化信息

       在Action中使用  : this.getText("msg");前提:action类要继承ActionSupport类。

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

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

 

例子:

  在cn.itcast.properties中写两个配置文件:

    msg_en_US.properties

      

name=tom

        msg_zh_CN.properties 

name=u6C64u59C6

    在struts.xml  配置

<struts>
    <package name="default" namespace="/" extends="struts-default">
        <action name="msg" class="cn.itcast.action.MsgAction">
            <result name="input">/fail.jsp</result>
        </action>
    </package>
    <constant name="struts.i18n.encoding" value="UTF-8"/>
    <constant name="struts.custom.i18n.resources" value="cn.itcast.properties.msg"></constant>
</struts>

    在action中打印(浏览器语言选择不同打印不同的结果)

              

package cn.itcast.action;

import com.opensymphony.xwork2.ActionSupport;

public class MsgAction extends ActionSupport {
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        System.out.println(this.getText("name"));
        return NONE;
    }
}

              

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

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

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

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

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

       在jsp指定读取 哪个properties文件

       <s:i18n name="cn.itcast.struts2.demo7.package">

              <s:text name="customer"></s:text>

       </s:i18n>

 5.在struts2中国际化配置文件中使用动态文本

1.action中怎样使用

 

msg=hello world {0}
this.getText("msg",new String[]{"tom"})

结果就是 hello world tom


2.jsp页面上怎样使用


msg=hello world {0}

<s:i18n name="cn.itcast.action.I18nDemo1Action">
<s:text name="msg">
<s:param>张三</s:param>
</s:text>
</s:i18n>

结果就是 hello world 张三.

 

 

原文地址:https://www.cnblogs.com/1963942081zzx/p/6488986.html