登录时更改区域设置

Ral*_*lph 13 java spring spring-security internationalization

我想在登录到使用Spring Security(3.0)的用户帐户Spring MVC Application(3.0)中存储的默认语言环境后更改语言环境.

我已经使用了LocaleChangeInterceptor这样一个(未登录,以及登录)用户可以更改其语言环境(默认来自accept标头).但客户确实希望该帐户具体默认.

所以我的问题是,登录后更改语言环境的最佳方法是什么,或者Spring/Security中是否已经有一些内置功能?

小智 9

我能找到的最佳解决方案是在AuthenticationSuccessHandler中处理这个问题.

以下是我为创业公司编写的一些代码:

public class LocaleSettingAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Resource
    private LocaleResolver localeResolver;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        setLocale(authentication, request, response);
        super.onAuthenticationSuccess(request, response, authentication);
    }

    protected void setLocale(Authentication authentication, HttpServletRequest request, HttpServletResponse response) {
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof LocaleProvider) {
                LocaleProvider localeProvider = (LocaleProvider) principal;
                Locale providedLocale = localeProvider.getLocale();
                localeResolver.setLocale(request, response, providedLocale);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并且您的主要课程应提供以下界面.这不是必需的,但我正在使用它,因为我有多个对象能够为会话提供区域设置.

public interface LocaleProvider {    
    Locale getLocale();    
}
Run Code Online (Sandbox Code Playgroud)

配置片段:

<security:http ...>
    <security:custom-filter ref="usernamePasswordAuthenticationFilter" position="FORM_LOGIN_FILTER"/>
</security:http>

<bean id="usernamePasswordAuthenticationFilter"
    class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
    <property name="filterProcessesUrl" value="/login/j_spring_security_check"/>
    <property name="authenticationManager" ref="authenticationManager"/>
    <property name="authenticationFailureHandler">
        <bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
            <property name="defaultFailureUrl" value="/login?login_error=t"/>
        </bean>
    </property>
    <property name="authenticationSuccessHandler">
        <bean class="LocaleSettingAuthenticationSuccessHandler">
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)