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 the Author

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

Comments

avatar
5 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
5 Comment authors
Saad BenbouzidmaksudarsansidBarry Recent comment authors
newest oldest most voted
Saad Benbouzid
Guest
Saad Benbouzid

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
Guest
mak

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

sudarsan
Guest
sudarsan

Thanks !

sid
Guest
sid

That worked !!

Barry
Guest
Barry

Awesome, your solution was spot-on. Thanks!