spring mvc国际化

2月 4, 2018 |

国际化由三个部分组成
1、国际化资源(message_zh_CN.properties)加载
2、localResolver的配置
3、页面添加<spring:message>元素,使用资源中的key
javacoder.cn整理, 转载注明出处
下面分别介绍

1、国际化资源(message_zh_CN.properties)加载

配置实现了MessageSource接口的bean

basenames表示资源文件的基础路径, 对于message_zh_CN.properties文件就为"message", 需要message_zh_CN.properties文件放在classes目录下,如果是其他目录请改为相应的路径
useCodeAsDefaultMessage表示properties文件中没有code对应的项时直接在页面输出code,而不是报错

新建两个properties文件
message_en_US.properties 内容如下
hello=hello {0} , {1}
message_zh_CN.properties内容如下
hello=\u4F60\u597D {0} , {1}

2、localResolver的配置

spring mvc默认配置的LocalResolver 为AcceptHeaderLocaleResolver, 根据http请求头"accept-language"来加载相应的国际化资源。
本例我们使用CookieLocaleResolver,如果cookie中有local信息我们就使用cookie中的,如果没有就是用CookieLocaleResolver的defaultLocale属性的值,如果defaultLocale属性没配置,那么使用http头" accept-header"的值。
配置如下

参考DispatcherServlet.initLocaleResolver()代码,CookieLocaleResolver的id必须为localeResolver, 不然不会使用的

3、<spring:message>使用

页面如下

添加一个设置cookie的处理方法

当用户点击相关的按钮后发送ajax改变语言, 然后window.location.reload();刷新页面,加载的就是如期望国际化后的页面
自己定制了<jctag:locale>tag来判断那个按钮被选中

效果如图:

4、内部原理介绍

无论是那种LocaleResolver的实现, DispatcherServlet.doService()将LocaleResolver添加到httpServletRequest中,便于页面渲染使用
org.springframework.web.servlet.support.RequestContext.initContext()方法中有如下代码
request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
大家仔细思考,这两处的localeResolver是同一个实例。
spring的ApplicationContext也实现了MessageSource接口, 所有查找资源时先去ApplicationContext中查找真正加载资源的MessageSource,也就是我们本例配置的ResourceBundleMessageSource

Posted in: spring practise

Comments are closed.