Spring i18n的better practice

Spring i18n 实践
本文探讨了在Spring框架中实现国际化(i18n)的方法。从基本的Java和JSP环境设置入手,介绍了如何利用Spring的MessageSource进行资源管理,增强了国际化支持。讨论了在实际项目中可能遇到的问题及最佳实践。
因为希望把springside搞成国际化项目,i18n就成了必做的事情。
照抄appfuse,折腾了很久后才发现appfuse式的sample总是只顾着演示自己的一亩三分地而忽略了很多其他东西。

1.从基础开始,没有spring时,java的i18n是这样的:
1.1 jsp环境
首先写一个messages.zh_cn.properties文件,放在class-path也就是/web-inf/classes里 welcome=欢迎 然后用native2ascii.exe把它转为 welcome=\u6b22\u8fce
在web.xml中定义messages文件 <context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationcontext</param-name>
<param-value>messages</param-value>
</context-param>
最后在jsp里使用
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
<fmt:message key="welcome"/>
如果有多个resource bundle文件, 就要在jsp里用<ftm:bundle>定义了.

1.2 pure java环境
resourcebundle rb = resourcebundle.getbundle("messages");
string welcome = rb.getstring("welcome");

2.spring的增强及appfuse的做法
spring增加了messagesource的概念,一是applicationcontext将充当一个单例的角色,不再需要每次使用i18时都初始化一次resourcebundle,二是可以代表多个resource bundle.

在applicationcontext的定义文件中,增加如下节点:
<bean id="messagesource" class="org.springframework.context.support.resourcebundlemessagesource">
<property name="basename" value="messages"/>
</bean>
则在pure java环境中。 context.getmessage("welcome", null, locale.china)

而在jsp环境中,controller调用jstl viewresolver再调用jsp时,<fmt:message>将继续发挥它的功效。

因此,appfuse等sample都是在appfuse-servlet.xml 中定义一个<messagesource>。

3.better practice
3.1 要不要定义javax.servlet.jsp.jstl.fmt.localizationcontext
appfuse等sample,都是假定大家完全使用controller作访问入口,jsp甚至藏在了/web-inf/中。而很不幸,大家的项目可能还是有很多直接访问jsp的地方,而直接访问jsp时,<messagesource>节点是没有作用的。
但如果定义了javax...localizationcontext, 又会让messagesource失效......


3.2 messagesource定义在applicationcontext.xml还是appfuse-servlet.xml
applicationcontext*.xml由contextloaderlistener载入,而appfuse-servlet.xml靠dispatchservlet载入,并拥有一个指向applcationcontex*.xml指针。所以,appfuse-servlet.xml能看到定义在applcationcontext里的东西,而反之做不到。
明显, 把<messagesource>定义在applicationcontext.xml 能获得更好的可见性。
但是appfuse没有在pure java代码中使用i18n,也就没有考虑这个问题。

3.3 坚决不用鸡肋级<spring:message> tag
连appfuse也不用它,可见多么鸡肋。因为fmt在找不到资源时,最多显示???welcome???,而<spring:message>则会抛出异常。

3.4 有趣的theme 解决"做成图片的文字"的国际化
theme也就是把message的原理发挥了一下,让不同语言的美术字图片的路径也可以定义在theme_zh_cn.properties和theme_en_us.properties中。终于有一个不那么鸡肋的spring tag了。

4.简单归纳

1. jstl中仍然使用标准的<ftm:message>及其定义?

2.java中使用spring的<messagesource>实现单例

3.用<spring:theme>解决那些做成图片的文字的国际化问题

4.spring 还有session,cookie locale resolver, 到时可以看一下.
文章来源:http://www.jiuyepx.cn/html/jishu/java/3250.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值