在前几天引用“Spring 的MVC I18N-国际化相关配置 ”并做了测试,发现 有一问题。程序运行会抛出异常
“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方法,源码示范如下
package org.springframework.web.servlet.i18n;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.LocaleResolver;
public class MyAcceptHeaderLocaleResolver extends AcceptHeaderLocaleResolver {
private Locale myLocal;
public Locale resolveLocale(HttpServletRequest request) {
return myLocal;
}
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
myLocal = locale;
}
}
然后在action-servlet.xml里的设置为
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="message" />
</bean>
<bean id="myViewController" class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />
<bean id="filenameController" class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors" ref="localeChangeInterceptor"/>
<property name="mappings">
<value>
chinese.do=filenameController
us.do=filenameController
</value>
</property>
</bean>
<bean id="defaultHandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.MyAcceptHeaderLocaleResolver"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>