`
wbj0110
  • 浏览: 1550624 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

spring mvc 3 国际化(上)——基础使用

阅读更多

spring mvc 国际化的基本使用

基本使用步骤

 

1.在spring的配置文件里加入

Xml代码  收藏代码
  1. <!-- Register the welcome.properties -->  
  2. <bean id="messageSource"  
  3.       class="org.springframework.context.support.ResourceBundleMessageSource">  
  4.     <!-- welcome为文件的前缀 ,message为文件夹 -->  
  5.     <property name="basenames" value="message/welcome"/>  
  6.     <property name="defaultEncoding" value="utf8" />  
  7. </bean>  

 

2.放入资源文件

message/welcome_en.properties

Properties代码  收藏代码
  1. welcome.springmvc = english title  

message/ welcome_zh.properties

Properties代码  收藏代码
  1. welcome.springmvc = chongwen title  

 

3.在jsp里使用

Html代码  收藏代码
  1. <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>  
  2. <h3>  
  3.     welcome.springmvc : <spring:message code="welcome.springmvc" text="default text" />  
  4. </h3>  

 

4.结束

上面3步就实现了spring的项目的国际化,默认使用的是头信息里的

Text代码  收藏代码
  1. Accept-Language:zh-CN,zh;q=0.8  

 来判断语言,(决定权在浏览器)

 

使用cookie或session来判断用户的语言

 

1.使用cookie

在spring配置文件中加入:

Xml代码  收藏代码
  1. <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">  
  2.      <property name="defaultLocale" value="en"/>  
  3.  </bean>  

 这是决定使用cookie来存储用户的语言,里面还可以配置用户的默认语言(也可以不配置)。

 

2.使用session

Xml代码  收藏代码
  1. <bean id="localeResolver"  
  2. class="org.springframework.web.servlet.i18n.SessionLocaleResolver">  
  3. <property name="defaultLocale" value="en"/>  
  4. </bean>  

 

 3.使用用户浏览器的语言(默认的采用的方法)

Xml代码  收藏代码
  1. <!--这个就是使用的http头信息里面的接收语言来判断用户的语言   -->  
  2.    <bean id="localeResolver"  
  3.    class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver">  
  4.    </bean>  

 

修改用户语言

1.使用

spring mvc的配置文件中插入

Xml代码  收藏代码
  1. <mvc:interceptors>  
  2.   <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">  
  3.   <property name="paramName" value="changeparam"/>  
  4.   </bean>  
  5.   </mvc:interceptors>  

 

这样就访问 http://localhost:8080?changeparam=en 就可以修改了

 

2.注意事项

使用浏览器来判断用户语言的方法不能修改,只有在使用Cookie和session的时候才可以修改用户语言。

 

代码中获取用户语言

 

Java代码  收藏代码
  1. request.getLocale()  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics