Spring 4 i18n & l10n (Cannot change HTTP accept header)

浪子不回头ぞ 提交于 2019-12-05 23:31:19

The problem lies in your configuration

@Bean
public SessionLocaleResolver sessionLocaleResolver() {
    SessionLocaleResolver localeResolver = new SessionLocaleResolver();
    localeResolver.setDefaultLocale(new Locale("en", "US"));
    return localeResolver;
}

This constructs a bean with the name sessionLocaleResolver however the DispatcherServlet looks for a bean with the name localeResolver. If this isn't detected it will use the default, which is a AcceptHeaderLocaleResovler.

The solution is quite simple rename your method to localeResolver or include a name attribute in the @Bean annotation.

@Bean
public LocaleResolver localeResolver() { ... }

or

@Bean(name="localeResolver")

From this blog post which helped solve my issue for the same,

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.

The solution was to declare this bean,

<bean id="localeResolver"
    class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
    <property name="defaultLocale" value="en" />
</bean>

I solved this issue by naming the method as localeResolver using the solution provided above by M.Deinum.

@Bean
public LocaleResolver localeResolver()
{
    final SessionLocaleResolver localeResolver = new SessionLocaleResolver();
    localeResolver.setDefaultLocale(new Locale("en", "US"));
    return localeResolver;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!