SpringMVC国际化设置-Cannot change HTTP accept header - use a different locale resolution strategy

来源:互联网 发布:南京软件开发有限公司 编辑:程序博客网 时间:2024/06/10 21:17

       使用SpringMVC3配置国际化,最近遇到了“Cannot change HTTP accept header - use a different locale resolution strategy” 这样的异常提示,最终解决了。现在来说说有关SpringMVC配置国际化的步骤及注意点,最后结合Spring源码解析下原理。

       国际化最常需要解决的问题

  1.       页面上能够根据浏览器设置的语言来动态展现文本,数值,时间等;
  2.       可以在Bean中获取设置的Locale信息;
  3.       可以通过动态链接的方式来切换locale信息。

        以下以demo的方式来说明以上三个问题的常用解决方法。

        问题1,解决方式如下:

        配置ResourceBundleMessageSource解析器,配置springmvc.xml如下:

       

<!-- 国际化 --><bean id="messageSource"class="org.springframework.context.support.ResourceBundleMessageSource"><property name="basename" value="i18n"></property></bean>

        增加i18n.properties配置文件,demo像征性的配置了一个中文,一个英文的,如下图:

     

            i18n_zh_CN.properties内容:

i18n.username = \u7528\u6237\u540Di18n.password = \u5BC6\u7801
          i18n_en_US.properties内容:
i18n.username = usernamei18n.password = passsword

           页面展现采用了JSTL的fmt标签:

<fmt:message key="i18n.username"></fmt:message>

有以上配置即可实现根据浏览器设置来展现 “用户名” 或是英文的 "username"


               问题2,在JAVA中在Bean中获取locale设置信息

           这个比较简单,在Bean中注入ResourceBundleMessageSource,即可获取到了,相关Java代码如下:


@Autowiredprivate ResourceBundleMessageSource messageSource;/** * 1.验证国际化配置根据本地语言配置动态,利用fmt标签动态展现 * 2.验证在Bean中获取国际化资源文件Locale对应的信息 */@RequestMapping("/i18n")public String testI18n(Locale locale) {String user = messageSource.getMessage("i18n.username", null, locale);System.out.println("国际化资源文件Locale配置(username):"+user);return "i18n";}

              问题3,再简单描述下就是在页面上动态设置语言信息,即动态设置locale信息以达到切换展现的目的,如下图:


在实现这个问题时遇到一个了标题中所写的报错,究其原因单步源码发现是由于localeResovler默认注入的是org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver,我们查看下这个类的setLocale方法会发现出现异常的原因了。

public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {/* 45 */     throw new UnsupportedOperationException("Cannot change HTTP accept header - use a different locale resolution strategy");/*    */   }

那么我们可以注入org.springframework.web.servlet.i18n.SessionLocaleResolver这个解析器来解决,这个解析器主要是将获取后Locale对象存于Session中供后续获取。

springmvc.xml配置如下:

<!-- 配置SessionLocaleResolver用于将Locale对象存储于Session中供后续使用 --><bean id="localeResolver"class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean><!-- 配置LocaleChangeInterceptor 主要用于获取请求中的locale信息,将期转为Locale对像,获取LocaleResolver对象-->    <mvc:interceptors>        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>    </mvc:interceptors>

这里有个特别需要注意bean id的配置,值必须为localeResolver否则,仍然会报标题中的错误。

按以上操作之后,就可以不用去浏览器手工设置语言了,可以直接通过上图中的 “中文”,“英文”进行切换,相信有些朋友会遇到这样的需求。

结合单步源码的过程,这里理解的内部原理用下图表示下:


       


0 0
原创粉丝点击