在我的 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/