您的位置:首页 > 编程语言 > Java开发

springframework(五)资源国际化

2016-07-29 00:00 555 查看
这里说的国际化不是简单的web层面的,也有纯后台层面的。因为spring不只是处理web的,也可以处理纯java的后台程序。这里也就是说aop、ioc、DI的使用是在整个java层面的而不是只局限于web项目中。

1、资源取得
资源的取得主要应用于国际化处理。在写程序的时候可以以不同的方式获取资源
例如:
// 直接从 classpath 中将文件信息取出,具体化称为一个资源文件对象
Resource resource = ctx.getResource( "classpath:admin.properties" );
// 从指定的硬盘路径中取得文件,具体实例化称为一个资源文件。
Resource resource1 = ctx.getResource( "file:c:/admin.properties" );
上边的“ classpath: ”是 spring 自制的 URL 虚拟协定,这会取得一个 org.springframework.core.io.ClasspathResource 实例,代表一个具体的资源文件。上边程序中,该资源文件是位于 Classpath 的根目录中,文件名称为 admin.properties ,你也可以指定标准的 URL, 像“ file: ”或“ http: ”

2、获取国际化资源的信息的方法:
A 、在 classpath 中定义国际化文件 messages_zh_CN.properties,messages_en_US.properties
例如:
hello = 用户{0} 于{1} 登陆系统
hello = user {0} login in system when {1}
B 、在配置文件list.xml中声明实现一个 ResourceBundleMessageSource 来取得国际化消息
例如:
< bean id = "messageSource" class = "org.springframework.context.support.ResourceBundleMessageSource" >
< property name = "basename" value = "messages" ></ property >
</ bean >
此处 bean id 必须是 messageSource
C 、编写测试程序

import java.util.Locale;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
//资源的取得和国际化
public class TestRes {
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("list.xml");
Object[] arguments = new Object[]{"管理员",java.util.Calendar.getInstance().getTime()};
System.out.println(ctx.getMessage("hello",arguments ,Locale.US));
System.out.println(ctx.getMessage("hello",arguments ,Locale.CHINA));
}
}


执行结果:
user 管理员 login in system when 3/15/09 10:10 AM
用户管理员于09-3-15 上午10:10登陆系统

总结下:
1、获取资源的方式有多样的
2、我们可以直接通过在spring的配置文件中声明国际化文件的名字,这里声明为messages,但是也要同时建立相对应的国际化文件messages_en_US.properties、messages_zh_US.properties
3、只要传送指定参数,指明要处理的语言,spring自动为我们将国际化文件中的内容取得,并且你还可以给国际化文件中的“占位符”传送参数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: