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>

Reference

  1. LocaleResolver documentation

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Saad Benbouzid
9 years ago

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 :

mak
9 years ago

Thanks a lot. This issue my wasted my time and i searched it everywhere but finally got and issue resolved.

sudarsan
11 years ago

Thanks !

sid
12 years ago

That worked !!

Barry
13 years ago

Awesome, your solution was spot-on. Thanks!