Main Tutorials

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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Saad Benbouzid
7 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
7 years ago

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

sudarsan
8 years ago

Thanks !

sid
9 years ago

That worked !!

Barry
11 years ago

Awesome, your solution was spot-on. Thanks!