Struts与Java的I18N国际化

  毫无疑问,Struts  的I18N是基于JAVA.UTIL.LOCALTE实现的,先简单说明两者的使用

     1.java中的I18N

  

I18NSerlvet
 1 package web.struts.i18n;
 2 
 3 import java.text.MessageFormat;
 4 import java.util.Locale;
 5 import java.util.ResourceBundle;
 6 import java.util.ResourceBundle.Control;
 7 
 8 public class Local_I18N {
 9     public static void ShowLocal(){
10         Locale[] ls=Locale.getAvailableLocales();
11         for(Locale l:ls){
12             System.out.println("contry:"+l.getDisplayCountry()+"===="+
13                     "languageCode"+l.getLanguage());
14         }
15     }
16     
17     public static void getLocal(){
18         //本地化工具类
19         //Locale l=Locale.getDefault(); //如果是中文系统,得到的是zh_CN
20         Locale l=new Locale("en", "US");
21         //将properties文件转存为键值对存储
22         
23         ResourceBundle rb=ResourceBundle.getBundle("web.struts.i18n.message",
24                 l,Local_I18N.class.getClassLoader());
25         String key_name= rb.getString("username");
26         //MessageFormate格式化字符串的类
27         String value=MessageFormat.format(key_name, "普通");
28         System.out.println("key=username"+"==="+"value="+value);
29     }
30     
31     public static void main(String[] args) {
32         ShowLocal();
33         getLocal();
34     }
35 }

  

message为JAVA的键值对的配置文件

     其中使用的类:Locale,MessageBunddle

   2.Struts中的I18N

1》资源配置文件

   在struts-default.xml

  定义了 <interceptor name="i18n" class="com.opensymphony.xwork2.interceptor.I18nInterceptor"/>

  国际化拦截器

 Struts2加载全局资源文件 
  加载全局资源文件的方式是通过配置常量来实现的。(struts.custom.i18n.resources) ,如果需要在项目中提供国际化功能,则需要指定struts.custom.i18n.resources常量,可以在struts.properties、struts.xml和web.xml中定义

在struts.properties中定义basename

struts.custom.i18n.resources=globalMessages

   在struts.xml中培植basename

  <constant name="struts.custom.i18n.resorces" value="globalMessages"/>

   在web.xml中定义

  <init-param>

   <param-name>struts.custom.i18n.resources</param-name>

  <param-value>globalMessages</param-value>

  </init-param>

2》 配置国际化所需要的资源键值对
为了实现国际化,必须先提供程序所需的资源文件(key-value对)。资源文件的命名可以有一下三种形式: 
baseName_language_country.properties 
 baseName_language.properties 
 baseName.properties 
其中baseName是资源文件的基本名,用户可以自由定义。而language和country都不是可以随便定义的,必须是Java所支持的语言和国家。 
若为非西欧字符集,则需要使用native2ascii转换工具转换为Unicode编码即可。

3》访问国际化资源
JSP页面输出:<s:text name=”username” />  用name属性来加载资源文件的key值。 
 Action中访问:可以使用ActionSupport类的getText方法。该方法可以接受一个name参数,既资源文件的key值。 
 表单元素的Label里输出:直接用对应表单的key属性。

4》输出带参数的国际化资源

 

 JSP页面输出:在<s:text name=”username” />标签中使用多个<s:param …/>

 

在视图中输出支持占位符的国际化资源信息需要使用标签苦,可以在<s:text../>标签中定义多个<s:param../>子元素来分别对应<s:text../>引用的国际化资源中的占位符
 Action中访问:使用getText(String aTextName,List args)或者getText(String key,String[] args)。

 

带占位符的:

 

 username=Your Name
password1=Password
birthday=Birthday
regsuccessmsg={0},Welcome!
regfaltmsg={0},Sorry!
welcomemsg=Hello {0},Now is{1}

 

 

原文地址:https://www.cnblogs.com/jerryxing/p/2474998.html