Spring 的MVC I18N-国际化相关配置出现的问题

 

今天用spring的mvc做国际化配置,出现了这样的错误

“Cannot change HTTP accept header - use a different locale resolution strategy”。

在网上找了一些资料,根本原因是spring source 做了限制,源码如下

public class AcceptHeaderLocaleResolver implements LocaleResolver {

 public Locale resolveLocale(HttpServletRequest request) {
  return request.getLocale();
 }

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

请注意上面的类,该类允许继承,所以需要改写setLocale方法,源码示范如下

 

  • localeResolver要用CookieLocaleResolver而不是AcceptHeaderLocaleResolver,若是后者则会抛出异常:
    throw new UnsupportedOperationException(”Cannot change HTTP accept header - use a different locale resolution strategy”);
  • message.properties是不能被作为默认或是英文识别的,资源文件必须加上_en或_zh之类的后缀,如message_en.properties和message_zh.properties

你可以使用LocaleChangeInterceptor修改本地化信息。这个拦截器需要被添加到处理器映射中它可以侦测请求中某个特定的参数,然后调用上下文中的LocaleResolver中的 setLocale()方法,相应地修改本地化信息。

package joddform;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;

public class MyAcceptHeaderLocaleResolver extends AcceptHeaderLocaleResolver{

 Locale myLocale;

 @Override
 public Locale resolveLocale(HttpServletRequest request) {
  return myLocale;
 }

 @Override
 public void setLocale(HttpServletRequest request,
   HttpServletResponse response, Locale locale) {
  myLocale = locale;
 }

}

<bean id="messageSource"
  class="org.springframework.context.support.ResourceBundleMessageSource">
  <property name="basenames">
   <list>
    <value>classpath*:i18n/error</value>
    <value>classpath*:i18n/message</value>
   </list>
  </property>
 </bean>

 <bean id="joddformhandlerMapping"
  class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
  <property name="mappings">
   <value>joddform.do=joddformController</value>
  </property>
  <property name="interceptors">
   <list>
    <ref bean="joddformInterceptor" />
    <ref bean="localeChangeInterceptor" />
   </list>
  </property>
 </bean>
 <bean id="joddformController" class="joddform.JoddformController">
 </bean>
 <bean id="joddformInterceptor"
  class="joddform.JoddformInterceptor">
 </bean>
 <bean id="localeChangeInterceptor"
  class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
  <property name="paramName" value="setLanguage" />
 </bean>
 
 <!--
 两种都可以,如果不改变默认的LocaleResolver的方法,就直接用CookieLocaleResolver
 千万记得这里bean的id一定是localeResolver,不然会找不到的
 更重要的一点是属性文件要带上_en,如在i18n包中如果写message.properties,它找不到英文文件
 所以,不管setLanguage如何设置都只能找到中文的属性文件
  -->

 <!--  
  <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"/>
 -->
 <bean id="localeResolver" class="joddform.MyAcceptHeaderLocaleResolver"></bean>

 

没有更多推荐了,返回首页