Struts1.X国际化源码解读

本文详细介绍了Struts框架实现国际化的过程,包括客户端如何通过HTTP头部发送语言偏好设置、服务器端如何根据这些设置加载对应的资源文件,以及Struts如何解析这些资源文件并返回本地化的消息。
回顾一下国际化的大概流程:client:IE/FF向服务器发送请求的同时,在html协议里的header里有accept-language字段,服务器接收后,把消息传递给Struts,Struts根据浏览器的发送过来的支持语言种类里选择对应的ApplicationResources_XX_XX_XX.properties。如果Struts里没有配置了对应的properties文件的话就采用默认的properties文件。在properties文件里的书写方式是如:error.username.null=username required!一行一对'键值对'。等号前面是key,等号后面是value。有了这个便于coder书写消息的规定之后,Struts对properties文件的解析就方便多了。下面来看看Struts是怎么取得Message的:
org.apache.struts.util.MessageResources里的getMessage方法
public String getMessage(Locale locale, String key, Object[] args) {
// Cache MessageFormat instances as they are accessed
if (locale == null) {
//源文件289行:protected Locale defaultLocale = Locale.getDefault();
locale = defaultLocale};
}
/*
源文件460到462中定义的方法体:
protected String messageKey(Locale locale, String key) {
return (localeKey(locale) + "." + key);
}
*/
MessageFormat format = null;
String formatKey = messageKey(locale, key);

synchronized (formats) {
// 86行定义了用于存放国际化消息的哈希表:protected HashMap formats = new HashMap();
format = (MessageFormat) formats.get(formatKey);
if (format == null) {
String formatString = getMessage(locale, key);

if (formatString == null) {
return returnNull ? null : ("???" + formatKey + "???");
}

format = new MessageFormat(escape(formatString));
format.setLocale(locale);
formats.put(formatKey, format);
}
}

return format.format(args);
}

大概说一下里面的处理流程把:在MessageResources类里,把properties解析后的'键值对'放在一个HashMap里,取出的时候,根据key来取。如果有复合消息文本的话就先对其'格式化'了在输出!
以上纯粹个人理解,谁看到错误了请不吝指正。共同进步!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值