国际化:假设开发一个支持多国语言的web应用程序,要求系统能够根据客户端的系统的语言类型返回对应的界面:英文操作系统返回英文界面,而中文的操作系统则返回对应的中文界面----这便是典型的i18n国际化的问题。
1.Locale
java.util.Locale 是表示语言和国家/地区信息的本地化类,是创建国际化应用的基础
@Test
public void handle2(){
Locale locale = new Locale("zh","CN");
//Locale locale = Locale.CHINA;
//Locale locale = Locale.ENGLISH;
//Locale locale = Locale.getDefault();
//System.out.println(locale.getCountry()+"==="+locale.getLanguage());
String str1 = "大家好!我是{0},{1}岁";
String str2 = "hello!I am{0},I am{1}";
Object[] params = new String[]{"moweng","20"};
MessageFormat messageFormat = new MessageFormat(str1, locale);
String mgs1 = messageFormat.format(str1);
System.out.println(mgs1);
}
2.MessageFormat 格式转化串
@Test
public void handle2(){
Locale locale = new Locale("zh","CN");
String str1 = "大家好!我是{0},{1}岁";
String str2 = "hello!I am{0},I am{1}";
Object[] params = new String[]{"moweng","20"};
MessageFormat messageFormat = new MessageFormat(str1, locale);
String mgs1 = messageFormat.format(str1);
System.out.println(mgs1);
}
3.ResourceBundle
(1)国际化资源文件的命名规则为:
<资源名>_<语言>_<国家/地区代码>.properties
假设资源名为resource,语言为英文,国家为美国,则与其对应的资源文件名为:resource_en_US.properties.信息在资源文件中以属性/值的方式表示:
name = keke
age = 30
(2)java提供了用于加载本地化资源文件的方便类java.util.ResourceBundle.
@Test
public void handle3(){
//Locale locale = Locale.CHINA;
Locale locale = Locale.US;
ResourceBundle resourceBundle = ResourceBundle.getBundle("resource",locale);
String str = resourceBundle.getString("name");
System.out.println(str);
}
4.MessageSource
spring 定义了访问国家化信息的MessageSource接口,并提供了几个实现类,该接口的方法有
(1)String getMessage(String code,Object[] args,String defaultMessage,Locale locale)
code 表示国际化资源中的属性名;args用于传递格式化串占位符所用的运行期参数;当在资源文件中找不到相对应的属性名时,返回defaultMessage参数所指定的默认信息,locale表示本地对象化
(2)String getMessage(String code,Object[] args,Locale locale) throws NoSuchMessageException
(3)String getMessage(MessageSourceResolvable resolvable,Locale lcoale) throws NoSuchMessageException
MessageSource的结构
例子:
@Test
public void handle4(){
Locale locale = Locale.CHINA;
//Locale locale = Locale.US;
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("resource");
Object[] param = new String[]{"keke","30"};
String str = messageSource.getMessage("name", param, locale);
System.out.println(str);
}
xml配置的方式
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>resource</value>
</list>
</property>
</bean>
测试:
@Test
public void handle5(){
Locale locale = Locale.CHINA;
//Locale locale = Locale.US;
ResourceBundleMessageSource messageSource = (ResourceBundleMessageSource)context.getBean("messageSource");
Object[] param = new String[]{"keke","30"};
String str = messageSource.getMessage("name", param, locale);
System.out.println(str);
}