Spring使用拦截器支持国际化(转)

Spring使用拦截器支持国际化很方便,使用时只须要两个步骤:web

一.spring配置spring

具体配置方式以下:浏览器

<!-- 资源文件绑定器,文件名称:messages.properties(没有找到时的默认文件), messages_en.properties(英文),messages_zh_CN.properties(中午),等等--> 
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> cookie

<property name="basename" value="config.messages.messages" /> session

</bean>mvc

<!-- 定义本地化变动拦截器 -->
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />app

<util:list id="interceptors">
<ref bean="localeChangeInterceptor" />
</util:list>url

<!-- 定义注解URL映射处理器 ,全部的请求映射必须关联本地化拦截器-->
<bean id="urlMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors" ref="interceptors" />
<property name="order" value="1"></property>
</bean>code

这时还须要本地化处理器进行处理,有三种处理器,以下:继承

<!-- 定义本地化处理器 -->

1. 基于session

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>

2. 基于请求

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver"/>
3.基于cookie

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />

以上三种处理器理论上配置任意一个就能够,不过有两点须要注意:

1)第二个不能直接使用,须要经过继承重写相应的方法,以下:

public class MyLocaleResolver extends AcceptHeaderLocaleResolver{

private Locale myLocal;
public Locale resolveLocale(HttpServletRequest request) {
return myLocal==null?request.getLocale():myLocal;
}
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
myLocal = locale;
}

}

修改配置文件中的localeResolver配置,class指向这个类就能够了。

2)第一与第三个用法相同,只不过前者使用session,session过时就须要从新设置,然后者使用cookie,能够根据项目的具体状况进行选择。

通常来讲,使用第一种和第三种比较常见。

二.使用方法

当不作处理时默认会使用浏览器本身的语言设置,若是想改变语言,只须要在请求后面加上一个参数便可,

默认的参数名为locale,里面放的就是你的提交参数,如:en_US,zh_CN之类的,

因此,只须要在页面上加上相应的连接便可,以下:

<a href="xxx.do?locale=zh_CN">中文</a>

<a href="xxx.do?locale=en">英文</a>

页面中使用jstl或spring标签,以下:

<fmt:message key="test.app"/>
<s:message code="test.app"/>

不管使用哪一种处理器,locale设置过一次就能够了,不须要每一个链接后面都加上locale参数。

相关文章
相关标签/搜索