Tomcat中的ResourceBundle国际化解析
一、ResourceBundle 简介:
资源束(ResourceBundle)是一个本地化对象。它封装了适用于本地环境的资源; 这个类主要用来解决国际化和本地化问题。国际化和本地化可不是两个概念,两者都是一起出现的。可以说,国际化的目的就是为了实现本地化。
比如对于“取消”,中文中我们使用“取消”来表示,而英文中我们使用“cancel”。若我们的程序是面向国际的(这也是软件发展的一个趋势),那么使用的人群必然是多语言环境的,实现国际化就非常有必要。而ResourceBundle可以帮助我们轻松完成这个任务:当程序需要一个特定于语言环境的资源时(如 String),程序可以从适合当前用户语言环境的资源包(大多数情况下也就是.properties文件)中加载它。这样可以编写很大程度上独立于用户语言环境的程序代码,它将资源包中大部分(即便不是全部)特定于语言环境的信息隔离开来。
这使编写的程序可以:
- 轻松地本地化或翻译成不同的语言
- 一次处理多个语言环境
- 以后可以轻松进行修改,以便支持更多的语言环境
说的简单点,这个类的作用就是读取资源属性文件(properties),然后根据.properties文件的名称信息(本地化信息),匹配当前系统的国别语言信息(也可以程序指定),然后获取相应的properties文件的内容。使用这个类,properties需要遵循一定的命名规范,一般的命名规范是: 自定义名_语言代码_国别代码.properties(LocalStrings_zh_CN.properties),如果是默认的,直接写为:自定义名.properties(LocalStrings.properties)
当在中文操作系统下,如果LocalStrings_zh_CN.properties、LocalStrings.properties两个文件都存在,则优先会使用LocalStrings_zh_CN.properties,当LocalStrings_zh_CN.properties不存在时候,会使用默认的myres.properties。在没有提供语言和地区的资源文件时使用的是系统默认的资源文件。
资源文件都必须是ISO-8859-1编码,因此,对于所有非西方语系的处理,都必须先将之转换为Java Unicode Escape格式。转换方法是通过JDK自带的工具native2ascii; 所以在中文资源文件中最好把中文转换为unicode, 否则可能会因为编译软件编码格式不一致而出现乱码问题
例如:
userConfig.start=\u7528\u6237\u914d\u7f6e\uff1a\u5904\u7406\u5f00\u59cb
二、ResourceBundle的使用
PropertyResourceBundle将本地化的文本存储于Java property文件中。
从ResourceBundle中获取值
- 获取ResourceBundle实例后可以通过下面的方法获得本地化值。
- getObject(String key);
- getString(String key);
- getStringArray(String key);
- 还可以通过keySet()方法获取所有的key。Set keys = bundle.keySet();
- 其它ResourceBundle 方法可以通过查看文档获得。
使用示例:
(1) 新建4个属性文件
my_en_US.properties:cancelKey=cancelmy_zh_CN.properties:cancelKey=\u53D6\u6D88(取消)my_zh.properties:cancelKey=\u53D6\u6D88zh(取消zh)my.properties:cancelKey=\u53D6\u6D88default(取消default)
(2) 获取bundle
ResourceBundle bundle = ResourceBundle.getBundle("res", new Locale("zh", "CN"));
注意: 其中new Locale(“zh”, “CN”)提供本地化信息,上面这行代码,程序会首先在classpath下寻找my_zh_CN.properties文件,若my_zh_CN.properties文件不存在,则取找my_zh.properties,如还是不存在,继续寻找my.properties,若都找不到就抛出异常。
(3) Test示例
import javax.annotation.Resource;
import java.util.Locale;
import java.util.ResourceBundle;/*** @author OovEver* 2018/1/14 22:12*/
public class Main {public static void main(String args[]) {ResourceBundle bundle = ResourceBundle.getBundle("my", new Locale("zh", "CN"));String cancel = bundle.getString("cancelKey");System.out.println(cancel);bundle = ResourceBundle.getBundle("my", Locale.US);cancel = bundle.getString("cancelKey");System.out.println(cancel);bundle = ResourceBundle.getBundle("my", Locale.getDefault());cancel = bundle.getString("cancelKey");System.out.println(cancel);bundle = ResourceBundle.getBundle("my", Locale.GERMAN);cancel = bundle.getString("cancelKey");System.out.println(cancel);bundle = ResourceBundle.getBundle("my");for (String key : bundle.keySet()) {System.out.println(bundle.getString(key));}}
}
(4) 输出结果
取消
cancel
取消
取消
取消
(5) 分析
前面三个分别按照zh_CN,US,默认的结果输出,第四个由于我们未定义GERMAN属性文件,这时ResourceBundle为我们提供了一个fallback(也就是一个备用方案),这个备用方案就是根据当前系统的语言环境来得到的本地化信息。所以若是找不到GERMAN的,之后就会去找CHINA了,所以找到了res_zh_CH.properties这个资源包。最后一个是若有多个属性文件,可以按照Map的形式遍历,获得属性文件内的各个值。
三、Tomcat中的ResourceBundle使用
Tomcat 的国际化管理是根据java文件包分类的; (比如操作系统为中文,那么通ResourceBundle.getBundle(org.apache.XXXX)所得到的本地资源束所指向的文件既是org.apaceh包下的XXXX_CN.properties)
Tomcat 维护了一个StringManager的集合。Tomcat将国际化资源信息存储在相应的包中。
(1) StringManager类中维护了一个StringManager集合
private static Hashtable managers = new Hashtable();
(2) StringManager类实现了对ResourceBundle资源束的管理,是ResourceBundle的封装
private final ResourceBundle bundle;
(3) 构造方法中实现了通过包名来取得本地环境指定包下的bundle
private StringManager(String packageName, Locale locale) {
String bundleName = packageName + ".LocalStrings";
ResourceBundle bnd = null;
try {
if (locale.getLanguage().equals(Locale.ENGLISH.getLanguage())) {
locale = Locale.ROOT;
}
bnd = ResourceBundle.getBundle(bundleName, locale);
} catch (MissingResourceException ex) {
. . .
}
bundle = bnd;
if (bundle != null) {
Locale bundleLocale = bundle.getLocale();
if (bundleLocale.equals(Locale.ROOT)) {
this.locale = Locale.ENGLISH;
} else {
this.locale = bundleLocale;
}
} else {
this.locale = null;
}
}
(4) 最后通过bundle.getString(key);方法,即可得到本地资源信息
public String getString(final String key, final Object... args) {
String value = getString(key);
if (value == null) {
value = key;
}MessageFormat mf = new MessageFormat(value);
mf.setLocale(locale);
return mf.format(args, new StringBuffer(), null).toString();
}
StringManager类:
package org.apache.tomcat.util.res;import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;public class StringManager {private static int LOCALE_CACHE_SIZE = 10;//此StringManager的ResourceBundleprivate final ResourceBundle bundle;private final Locale locale;/*** Creates a new StringManager for a given package. This is a* private method and all access to it is arbitrated by the* static getManager method call so that only one StringManager* per package will be created.** @param packageName Name of package to create StringManager for.*/private StringManager(String packageName, Locale locale) {String bundleName = packageName + ".LocalStrings";ResourceBundle bnd = null;try {// The ROOT Locale uses English. If English is requested, force the// use of the ROOT Locale else incorrect results may be obtained if// the system default locale is not English and translations are// available for the system default locale.if (locale.getLanguage().equals(Locale.ENGLISH.getLanguage())) {locale = Locale.ROOT;} bnd = ResourceBundle.getBundle(bundleName, locale);} catch (MissingResourceException ex) {// Try from the current loader (that's the case for trusted apps)// Should only be required if using a TC5 style classloader structure// where common != shared != serverClassLoader cl = Thread.currentThread().getContextClassLoader();if (cl != null) {try {bnd = ResourceBundle.getBundle(bundleName, locale, cl);} catch (MissingResourceException ex2) {// Ignore}}}bundle = bnd;// Get the actual locale, which may be different from the requested oneif (bundle != null) {Locale bundleLocale = bundle.getLocale();if (bundleLocale.equals(Locale.ROOT)) {this.locale = Locale.ENGLISH;} else {this.locale = bundleLocale;}} else {this.locale = null;}}/*** Get a string from the underlying resource bundle or return null if the* String is not found.** @param key to desired resource String** @return resource String matching <i>key</i> from underlying bundle or* null if not found.** @throws IllegalArgumentException if <i>key</i> is null*/public String getString(String key) {if (key == null){String msg = "key may not have a null value";throw new IllegalArgumentException(msg);}String str = null;try {// Avoid NPE if bundle is null and treat it like an MREif (bundle != null) {str = bundle.getString(key);}} catch (MissingResourceException mre) {//bad: shouldn't mask an exception the following way:// str = "[cannot find message associated with key '" + key +// "' due to " + mre + "]";// because it hides the fact that the String was missing// from the calling code.//good: could just throw the exception (or wrap it in another)// but that would probably cause much havoc on existing// code.//better: consistent with container pattern to// simply return null. Calling code can then do// a null check.str = null;}return str;}/*** Get a string from the underlying resource bundle and format* it with the given set of arguments.** @param key The key for the required message* @param args The values to insert into the message** @return The request string formatted with the provided arguments or the* key if the key was not found.*/public String getString(final String key, final Object... args) {String value = getString(key);if (value == null) {value = key;}MessageFormat mf = new MessageFormat(value);mf.setLocale(locale);return mf.format(args, new StringBuffer(), null).toString();}/*** Identify the Locale this StringManager is associated with.** @return The Locale associated with the StringManager*/public Locale getLocale() {return locale;}// --------------------------------------------------------------// STATIC SUPPORT METHODS// --------------------------------------------------------------private static final Map<String, Map<Locale,StringManager>> managers =new Hashtable<>();/*** Get the StringManager for a given class. The StringManager will be* returned for the package in which the class is located. If a manager for* that package already exists, it will be reused, else a new* StringManager will be created and returned.** @param clazz The class for which to retrieve the StringManager** @return The instance associated with the package of the provide class*/public static final StringManager getManager(Class<?> clazz) {return getManager(clazz.getPackage().getName());}/*** Get the StringManager for a particular package. If a manager for* a package already exists, it will be reused, else a new* StringManager will be created and returned.** @param packageName The package name** @return The instance associated with the given package and the default* Locale*/public static final StringManager getManager(String packageName) {return getManager(packageName, Locale.getDefault());}/*** Get the StringManager for a particular package and Locale. If a manager* for a package/Locale combination already exists, it will be reused, else* a new StringManager will be created and returned.** @param packageName The package name* @param locale The Locale** @return The instance associated with the given package and Locale*/public static final synchronized StringManager getManager(String packageName, Locale locale) {Map<Locale,StringManager> map = managers.get(packageName);if (map == null) {/** Don't want the HashMap to be expanded beyond LOCALE_CACHE_SIZE.* Expansion occurs when size() exceeds capacity. Therefore keep* size at or below capacity.* removeEldestEntry() executes after insertion therefore the test* for removal needs to use one less than the maximum desired size**/map = new LinkedHashMap<Locale,StringManager>(LOCALE_CACHE_SIZE, 1, true) {private static final long serialVersionUID = 1L;@Overrideprotected boolean removeEldestEntry(Map.Entry<Locale,StringManager> eldest) {if (size() > (LOCALE_CACHE_SIZE - 1)) {return true;}return false;}};managers.put(packageName, map);}StringManager mgr = map.get(locale);if (mgr == null) {mgr = new StringManager(packageName, locale);map.put(locale, mgr);}return mgr;}/*** Retrieve the StringManager for a list of Locales. The first StringManager* found will be returned.** @param packageName The package for which the StringManager was* requested* @param requestedLocales The list of Locales** @return the found StringManager or the default StringManager*/public static StringManager getManager(String packageName,Enumeration<Locale> requestedLocales) {while (requestedLocales.hasMoreElements()) {Locale locale = requestedLocales.nextElement();StringManager result = getManager(packageName, locale);if (result.getLocale().equals(locale)) {return result;}}// Return the defaultreturn getManager(packageName);}
}
Tomcat中的ResourceBundle国际化解析相关推荐
- tomcat中request对象是被创建的_常用开源框架中设计模式使用分析(全)
一.前言 说起来设计模式,大家应该都耳熟能详,设计模式代表了软件设计的最佳实践,是经过不断总结提炼出来的代码设计经验的分类总结,这些模式或者可以简化代码,或者可以是代码逻辑开起来清晰,或者对功能扩展很 ...
- tomcat源码之架构解析
1. Tomcat的整体框架结构 Tomcat的基本框架, 分为4个层次. Top Level Elements: Server Service Connector ...
- Tomcat中容器的pipeline机制
本文主要目的是讲解tomcat中的pipeline机制,涉及部分源码分析 之前我们在前面的文章介绍过,tomcat中Container有4种,分别是Engine,Host,Context,Wrappe ...
- Jenkins 在 Tomcat 中的部署及代码静态检查工具集成
Jenkins 的简单部署 在安装了 Jenkins 运行所需的依赖(主要是 JDK)之后,可以通过如下步骤简单快速地部署 Jenkins: 下载 Jenkins. 打开终端并切换至下载目录. 运行命 ...
- 解决tomcat中temp文件夹出现项目的副本的情况
解决tomcat中temp文件夹出现项目的副本的情况 TomcatMyeclipseXMLGoogle 在最近开发过程中出现过这样的情况,当我在myeclipse发布项目的时候,在tomcat的te ...
- Tomcat中的连接器是如何设计的
上期回顾 上一篇文章<Tomcat在SpringBoot中是如何启动的>从main方法启动说起,窥探了SpringBoot是如何启动Tomcat的,在分析Tomcat中我们重点提到了,To ...
- Tomcat中如何配置使用APR
APR(Apache Portable Runtime),即Apache可移植运行库,正如官网所言,APR的使命是创建和维护一套软件库,以便在不同操作系统(Windows.Linux等)底层实现的基础 ...
- Tomcat 中的可插拔以及 SCI 的实现原理
Tomcat 中的可插拔以及 SCI 的实现原理 转载: 侯树成 Tomcat那些事儿 2017-09-19 引子 常用计算机的朋友一定记得, U盘,硬盘等设备流行的时候,当时对于这项技术的介绍是热插 ...
- ios5中apple增加了解析JSON的api——NSJSONSerialization。
ios5中apple增加了解析JSON的api--NSJSONSerialization.网上已经有人做过测试,NSJSONSerialization在效率上完胜SBJSON.TouchJSON.YA ...
- python中利用lxml模块解析xml文件报错XMLSyntaxError: Opening and ending tag mismatch
今天在代码中第一次使用lxml解析xml文件时出错了, XMLSyntaxError: Opening and ending tag mismatch: keyEffectiveDate line 2 ...
最新文章
- Trie树统计单词前缀
- DCMTK:将轮廓数据添加到RT结构集中的测试程序
- 《假如编程是魔法之零基础看得懂的Python入门教程 》——(三)使用初始魔法跟编程魔法世界打个招呼吧
- Hibernate之必须导入jar包
- mysql 二维数组下标_php二维数组指定下标排序
- markdown html vue,vue项目引入markdown
- DFS实现floodfill算法
- Magento教程 2:Magento 社群版安装教学!
- 谷歌大脑推出视觉领域任务自适应基准:VTAB
- 基片集成波导原理_第5讲基片集成波导.ppt
- ThreadPool执行异步操作
- 制作粉色少女系列❤生日快乐祝福网页❤(HTML+CSS+JS)
- word文档中打钩的8种方法【实用】
- 医院电子病历系统HIS、LIS、PACS、CIS源码
- 如何用SPSS或Excel做中介效应的Sobe检验?
- java近义词,java实现近义词维护
- 悦诗风吟网络营销的目标_悦诗风吟产品网络营销推广策划方案
- MTK平台TP驱动详解
- MXNet网络模型(四)GAN神经网络
- 中国凝油锅炉市场趋势报告、技术动态创新及市场预测