该文章基于《Spring+MyBatis企业应用实战》进行总结,旨在积累巩固
SpringMVC的国际化按照如下步骤进行:
(1)加载国际化资源文件
(2)输出国际化资源,输出国际化资源需要分为在view层输出国际化资源,在Controller中输出国际化消息
加载国际化资源
国际化文件
文件类型为.properties,文件名称格式为XXX_en_US,内容格式为key = value,该文件最好放置在src文件夹中。
messageSource配置
该配置用于加载国际化文件,在对应模块的Servlet中的[servletname]-config.xml中进行配置:
<bean class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>XXX</value>
</list>
</property>
</bean>
国际化拦截器
该配置通过国际化拦截器来匹配对应的国际化资源:
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
</mvc:interceptors>
localResolver配置
获取语言时区的方法基于语言解析器接口LocalResolver,常用实现类如下:
1.AcceptHeaderLocalResolver(默认),该解析器通过读取浏览器的accept-language标题来确定
2.SessionLocalResolver,sessionLocalResolver可以解决的问题就是用户想要主动设置语言环境,国际化资源的加载是透明的,我们只需要在Controller中获取用户的提交参数之后通过如下的方法进行设置:
Local local = new Local("en_US");
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,local);
3.CookieLocalResolver,其目的大致与SessionLocalResolver相同,Controller中的设定稍微有不同:
Local local = new Local("en_US");
(new CookieLocalResolver()).setLocal(request,response,locale);
LocalResolver的配置方式如下:
<bean id="localResolver" class="org.springframework.web.servlet.i18n.XXX"/>
输出国际化资源
view层
首先需要在Jsp页面中通过导入标签库:
<%@taglib prefix= "spring" uri= "http://www.springframework.org/tags" %>
然后直接通过使用标签:
<spring:message code="需要输出信息的key">
Controller层
Controller层使用国际化资源需要借助于RequestContext对象的getMessage方法来进行获取国际化消息,一般可以使用HttpServletRequest和HttpServletResponse来进行RequestContext的初始化。