导言
很多面对全世界的网站或者软件都需要适应不同语言环境的人,这就需要程序或者网页能够很简便地切换语言种类,这就是Spring MVC的国际化。
资源文件
一般命名格式为:baseName_language_country.properties
例如中国大陆:baseName_zh_CN.properties,在该文件加入:
“hello=我要向不同的人民问号:你好!”,添加以后保存,系统会自动进行UNicode编码
带占位符的国际化信息
资源文件中的信息文本可以带有参数,例如
welcome={0},你好,今今天星期{1}。
那么如何替换占位符呢?下面有一个例子:
public static void main(String[] args) {
//取得系统默认的国家语言环境
Locale lc = Locale.getDefault();
//根据国际语言环境加载资源文件
ResourceBundle rb = ResourceBundle.getBundle("messageResource", lc);
//从资源文件中过去信息
String msg = rb.getString("welcome");
//替换消息文本中的占位符,就是"{0}"和"{1}",消息文本中的占位符按照参数的顺序
//(cong第二个参数开始)被替换,也就是"马云"替换"{0}",“5”替换"{1}"
String msgFor = MessageFormat.format(msg, "马云","5");
System.out.println(msgFor);
接下来就是重点了。。。
Spring MVC 的国际化
接下来继续探索如何选择和读取正确位置的资源属性文件
首先肯定要在springmvc-servlet.xml中加载资源属性文件
<!-- 加载国际化资源文件 -->
<bean id = "messageSource" class = "org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value ="/WEB-INF/resource/messages" />
</bean>
解释一波:"/WEB-INF/resource/messages" 是资源文件的位置
这里注意两点:
- 如果修改了国际化资源文件,就要重新启动JVM
- 如果有一组属性文件,basenames要替换掉basename,用来复数嘛。
其次就是语言区域的选择
这里只介绍CookieLocaleResolver,它比较方便用户选择喜欢的语言种类
<bean id ="localeResolver" class = "org.springframework.web.servlet.i18n.SessionLocaleResolver" >
<property name="defaultLocale" value = "zh_CN"> </property>
</bean>
同时必须要配置LOcaleChangeInterceptor拦截器,配套使用:
<mvc:interceptors>
<bean class ="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
</mvc:interceptors>
再者,就需要使用message标签显示国际化信息
需要在jsp中声明:
<%@taglib prefix = "spring" uri = "http://www.springframework.org/tags" %>
message标签有几个常用的属性:
- code:获得国际化信息的key
- arguments:代表该标签的参数,就是上面可以替换占位符的
- text:code属性不存在,或指定的key无法获取信息时默认显示的信息
例如:
<a href="${pageContext.request.contextPath }/i18nTest?locale=zh_CN">
<spring:message code="language.cn"/></a>--
<a href="${pageContext.request.contextPath }/i18nTest?locale=en_US">
<spring:message code="language.en"/></a>
<br><br>
<spring:message code="first"/><br><br>
<a href = "${pageContext.request.contextPath }/my/second">
<spring:message code="second"/></a>
实例演示:
可随意转换语言