spring mvc 国际化配置

本文介绍了如何在Spring MVC中配置国际化,主要通过MessageSource管理国际资源文件,包括基于浏览器默认语言、Cookie和Session的三种实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

要使用spring mvc配置国际化,首先用MessageSource来管理国际资源文件:

 <!-- 国际化资源文件 messageSource配置的是国际化资源文件的路径, 
classpath:messages指的是classpath路径下的 messages_zh_CN.properties文件和messages_en_US.properties文件 
设置“useCodeAsDefaultMessage”,默认为false,这样当Spring在ResourceBundle中找不到messageKey的话,就抛出NoSuchMessageException, 把它设置为True,则找不到不会抛出异常,而是使用messageKey作为返回值。 -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
        <property name="defaultEncoding" value="UTF-8" />  
        <property name="useCodeAsDefaultMessage" value="true" />  
        <property name="cacheSeconds" value="10"></property>  
        <property name="basenames">  
            <list>  
                <value>classpath:messages</value>  
            </list>  
        </property>  
</bean>

主要有三种方式:

  • 默认为基于浏览器(以谷歌浏览器为例,设置语言的首选项即为默认语言,Accept-Language)

 

  • 基于Cookie

<!--CookieLocaleResolver解析会检查客户端是否有Cookie,里面可能存放了地区Locale或时区TimeZone信息。如果检查到相应的值,解析器就使用它们。通过该解析器的属性,你可以指定cookie的名称和其最大的存活时间。-->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
    <property name="cookieName" value="clientlanguage"/>
    <!-- 单位为秒。若设置为-1,则cookie不会被持久化(客户端关闭浏览器后即被删除) -->
    <property name="cookieMaxAge" value="100000">
</bean>
<mvc:interceptors>  
    <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置,这个拦截器会拦截请求中的参数,然后根据参数去调用LocaleResolver的setLocale()方法,改变当前的locale值 --> 
    <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />  
</mvc:interceptors>  
  • 基于Session

<mvc:interceptors>  
    <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 --> 
    <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />  
</mvc:interceptors>  

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值