java - 登录时更改语言环境

标签 java spring internationalization spring-security

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

我已经使用了 LocaleChangeInterceptor,因此(未登录以及已登录的)用户可以更改其区域设置(默认来自接受 header )。但客户确实想要该帐户特定的默认值。

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

最佳答案

我能找到的最佳解决方案是在 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);
            }
        }
    }
}

您的主体类应提供以下接口(interface)。 这不是必需的,但我正在使用它,因为我有多个能够为 session 提供语言环境的对象。

public interface LocaleProvider {    
    Locale getLocale();    
}

配置片段:

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

关于java - 登录时更改语言环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8531649/

相关文章:

java - java中打印数组元素的数据

java - 关闭网络连接时显示先前加载的数据的技术

java - 你能反射(reflection)一下Java中的私有(private)静态方法吗

c++ - boost 正则表达式 : [:alpha:] and accented characters

internationalization - 对大文本值进行小的编辑时如何有效地处理 gettext PO 文件

java - 将 Web Controller 添加到 Akka Actor 系统

java - Spring 集成 Kinesis - 未找到正确的实现

java - 与 DBCP 连接池和线程的混淆

java - Spring Social Facebook 2.0.2 无法获取电子邮件

ruby-on-rails - 区域设置更改时如何使片段缓存过期?