i need to change locale settings after successful Authentication.
LocaleResolver:
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lng" />
</bean>
<bean id="localeResolver"
class="web.MyLocaleResolver">
</bean>
public class MyLocaleResolver extends AbstractLocaleResolver {
private Locale default = Locale.ENGLISH;
@Override
public Locale resolveLocale(HttpServletRequest hsr) {
return this.default;
}
@Override
public void setLocale(HttpServletRequest hsr, HttpServletResponse hsr1, Locale default) {
this.default = default;
}
}
Security:
<form-login login-page="/login"
authentication-success-handler- ref="MySuccessAuthHandler"/>
<beans:bean id="MySuccessAuthHandler" class="web.MySuccessfulAuthenticationHandler">
<beans:property name="defaultTargetUrl" value="/index.htm"></beans:property>
</beans:bean>
public class MySuccessfulAuthenticationHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
super.onAuthenticationSuccess(request, response, authentication);
RequestContextUtils.getLocaleResolver(request).setLocale(request, response, Locale.ENGLISH);
}
}
When i try to set locale by RequestContextUtils
i get NullPointer Exception.
Even though the DispatcherServlet isn't normally reached when using Spring Security, you can add the RequestContextFilter BEFORE your security filter chain which exposes all the request attributes like the localeResolver.
Even though this should make your example work. For other people: another option is to use
WebApplicationContextUtils.getWebApplicationContext(ServletContext)
passing it the ServletContext that is available in the HttpServletRequestThe solution from Kafkaesque is not complete.
But even spring security documentation is wrong:
see https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#localization
You can not use
RequestContextFilter
as this filter is not aware of anyLocaleResolver
inside your applicationContext. It just uses the Locale fromrequest.getLocale()
which is theAccept-Language
Header.If you want to use your own LocaleResolver in this filter you need to write your own:
and then configure your web.xml
LocaleResolver
is exposed in request context byDispatcherServlet
, whereasAuthenticationSuccessHandler
is fired before request entersDispatcherServlet
(actually, request that firedSavedRequestAwareAuthenticationSuccessHandler
never entersDispatcherServlet
, because this handler performs a redirect).Thus, you cannot access
LocaleResolver
viaRequestContextUtils
in this case. You can try to injectLocaleResolver
into yourAuthenticationSuccessHandler
explicitly, for example, with autowiring.