Spring使用拦截器支持国际化(转)
2013-12-30 11:38
351 查看
Spring使用拦截器支持国际化(转)
(2012-04-23 13:51:34)![](http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif)
转载▼
标签:
| 分类: SSH |
一.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参数。
相关文章推荐
- Spring使用拦截器支持国际化(转)
- 7.4.3: 使用spring容器---ApplicationContext的国际化支持
- 7 -- Spring的基本用法 -- 4... 使用 Spring 容器:Spring 容器BeanFactory、ApplicationContext;ApplicationContext 的国际化支持;ApplicationContext 的事件机制;让Bean获取Spring容器;Spring容器中的Bean
- SpringBoot使用拦截器
- Spring对 JDBC 的支持,JdbcTemplate类的使用
- SpringBoot学习-支持PageHelp插件使用
- Spring Boot中的缓存支持(二)使用Redis做集中式缓存
- 使用Spring对JDBC的Dao的支持类操作数据库
- 使用Spring Boot开发Web项目(二)之添加HTTPS支持
- SpringMVC + FreeMarker 国际化使用方法
- SpringBoot学习笔记之拦截器使用
- 使用Spring的JAVA Mail支持简化邮件发送
- Spring ORM 框架支持优势Spring还在测试、数据源管理方面提供支持,从而允许方便测试,简化数据源使用。
- 使用方法拦截器MethodInterceptor和AOP统一处理log (Spring的拦截器 对方法进行拦截 ))
- 使用Spring Boot开发Web项目(二)之添加HTTPS支持
- 使用MVP注册登录模块+封装的OKhttp,拦截器+QQ第三方登录+RecyclerView+SpringView上拉加载下拉刷新网络数据
- Spring 拦截器的使用
- Spring Boot中的缓存支持(二)使用Redis做集中式缓存
- SpringBoot使用拦截器
- 使用Spring中的IoC功能来实现我们所开发项目系统的国际化