您的位置:首页 > 编程语言 > Java开发

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

2013-12-30 11:38 351 查看


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

(2012-04-23 13:51:34)


转载▼

标签:


it

分类: SSH
Spring使用拦截器支持国际化很方便,使用时只需要两个步骤:

一.spring配置

具体配置方式如下:

<!-- 资源文件绑定器,文件名称:messages.properties(没有找到时的默认文件), messages_en.properties(英文),messages_zh_CN.properties(中午),等等-->

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">

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

</bean>

<!-- 定义本地化变更拦截器 -->

<bean id="localeChangeInterceptor"

class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />

<util:list id="interceptors">

<ref bean="localeChangeInterceptor" />

</util:list>

<!-- 定义注解URL映射处理器 ,所有的请求映射必须关联本地化拦截器-->

<bean id="urlMapping"

class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">

<property name="interceptors" ref="interceptors" />

<property name="order" value="1"></property>

</bean>

这时还需要本地化处理器进行处理,有三种处理器,如下:

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

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参数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: