Cannot change HTTP accept header – use a different locale resolution strategy
Problem
In Spring MVC application, while changing the locale with “org.springframework.web.servlet.i18n.LocaleChangeInterceptor“, it hits the following error
java.lang.UnsupportedOperationException:
Cannot change HTTP accept header - use a different locale resolution strategy
...AcceptHeaderLocaleResolver.setLocale(AcceptHeaderLocaleResolver.java:45)
Solution
In Spring MVC application, if you do not configure the Spring’s LocaleResolver, it will use the default AcceptHeaderLocaleResolver, which does not allow to change the locale. To solve it, try declare a SessionLocaleResolver bean in the Spring bean configuration file, it should be suits in most cases.
<beans ...
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="language" />
</bean>
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" >
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor" />
</list>
</property>
</bean>
</beans>
Note that bean name “localeResolver” is mandatory, as described in the org.springframework.web.servlet.DispatcherServlet implementation when bootstrapping the spring-mvc servlet :
org.springframework.web.servlet.DispatcherServlet:
initLocaleResolver(ApplicationContext context) {
this.localeResolver = context.getBean(“localeResolver”, LocaleResolver.class);
}
which would be either :
@Bean(name = DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME)
public SessionLocaleResolver sessionLocaleResolver() {
final SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
sessionLocaleResolver.setDefaultLocale(Locale.FRANCE);
return sessionLocaleResolver;
}
or :
Thanks a lot. This issue my wasted my time and i searched it everywhere but finally got and issue resolved.
Thanks !
That worked !!
Awesome, your solution was spot-on. Thanks!