最近在做一个项目,因为同时涉及到国内及国外的客户,所以需要对项目做国际化,不管是页面显示,还是后台交互的模板,都要做出正确的响应。
因为前面用到的是Spring MVC,而Spring对国际化的支持已经非常完善,所以只需要一些简单的配置即可完成。
第一步:添加applicationContext-i18n.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:/messages/messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="zh" />
</bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="l" />
</bean>
</mvc:interceptors>
</beans>
并将applicationContext-i18n.xml导入到dispatcher-servlet.xml文件中<import resource="applicationContext-i18n.xml" />
第二步:创建messages.properties
假设支持中文和英文,则需要分别创建 messages_en.properties和messages_zh.properties两个文件
messages_en.propertieshello.defei=Hello Defei!
messages_zh.propertieshello.defei=你好 德飞!
将这两个文件放入messages文件夹里,messages放到属性为classpath的目录下就可以了。
第三步:页面显示
- 引入Spring标签库:
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
- 输出信息
<spring:message code="hello.defei" />
这样就能根据浏览器自动切换语言了,我想有的朋友已经注意在前文中添加了一个SessionLocaleResolver和LocaleChangeInterceptor,有了这两个bean就可以手动更新locale了,如下:
<div class="change-language">
<a href="?l=en">English</a>|<a href="?l=zh">中文</a>
</div>
这样就能随意切换显示语言了。
到这里,国际化已经可以用了。如果您还需要后台进行国际化响应,那么下面的资料你可以参考下 :)
在Spring MVC controller的响应方法上,加上参数(Locale locale),Spring MVC就会自动注入当前请求的Locale信息,后台就够根据locale做出相应的响应了。
当然也可以调用静态方法LocaleContextHolder.getLocale()
,得到当前线程所请求的Locale信息,原理是基于ThreadLocal实现的。
如果在后台需要获取定义的message.properties数据,只需要注入ReloadableResourceBundleMessageSource :
@Autowired
private ReloadableResourceBundleMessageSource messageSource;
然后在代码里面就能取到对应的message了.String message = messageSource.getMessage("hello.defei", null, locale);
如果是传参的message,用法如下:
message.propertieswelecome.sb.to.sw=Hi {0}, welcome to {1}.
jsp page:<spring:message code="welecome.sb.to.sw" arguments="${name},${country}" />
java code:String message = messageSource.getMessage("welecome.sb.to.sw", new Object[]{"Defei","China"}, locale);

