java - 在 Spring Security 登录期间设置 Grails/Spring Locale - 如何?

标签 java spring grails spring-security locale

在我的 Grails 1.3.7 应用程序中,我将用户的语言和国家/地区存储在域类中。

在 (Spring Security) 登录期间,我想将用户 session 的语言环境设置为为此用户存储的语言/国家/地区。

我正在实现我的自定义监听器,在 grails-app/spring/resources.groovy 中注册:

class MyListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {
    def config = org.codehaus.groovy.grails.commons.ConfigurationHolder.config

    void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) {
            User user = User.findByUsername(event.authentication.name)
            Locale locale = new Locale(user.getLanguage(), user.getCountry())

            LocaleContextHolder.setLocale(locale)
            HttpServletRequest request = SecurityRequestHolder.request
            HttpServletResponse response = SecurityRequestHolder.response
            LocaleResolver locRes = RequestContextUtils.getLocaleResolver(request)

            locRes.setLocale(request, response, locale)
    }
}

我的问题是 RequestContextUtils.getLocaleResolver 返回 null。

如何设置新的语言环境?

最佳答案

与其在登录步骤中执行此操作,不如创建一个 LocaleResolver可以确定用于给定 HttpServletRequest 的正确 Locale 的实现。

您的应用需要知道如何为用户发出的每个后续请求解析区域设置。在 LocaleResolver 或 LocaleContextHolder 中手动设置 Locale 只会影响为当前请求存储 Locale 的 ThreadLocal。新请求将不会具有相同的 ThreadLocal,并且会看到未设置的区域设置。

创建一个从 Spring Security 上下文中获取当前登录的 UserDetails 并找到用户的 Locale 的实现应该是微不足道的(或者您可以将详细信息存储在 Session 等中) ., 选择权在你手中)。

关于java - 在 Spring Security 登录期间设置 Grails/Spring Locale - 如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7915272/

相关文章:

java - 编码bat ap考试练习

java - web-app 的 context-param 和 servlet 的 init-param 之间的区别?

java - Spring MVC @NumberFormat 带小数的百分比

grails - 命令对象中的 java.lang.NullPointerException

java - 如何向JComponent添加多个对象?

java - Postgresql 未使用 JDBC 连接到 android,抛出 org.postgresql.util.PSQLException : The connection attempt failed

java - 如何在spring Mvc中使用多线程提高性能

grails - Grails 2.5.4 中的 GORM 触发模式

email - Grails邮件插件:查看的绝对路径

java - 在 sqlite 数据库中插入日期和时间时出错