Grails - 更改区域设置行为以使用破折号而不是下划线

Shl*_*rtz 3 grails locale request internationalization web

我正在写一个Grails应用程序,它是第三方的区域设置,如下所示:

my.app.com?lang= zh-CN,因为Grails使用en_US会抛出异常Error intercepting locale change: Locale part "en-US" contains invalid characters

如何在PageFragmentCachingFilter之前拦截请求,以便修复语言环境代码?

有更好的方法吗?

dma*_*tro 6

覆盖默认行为的一种方式是注册一个CustomLocaleChangeInterceptor作为一个bean resources.groovy作为

beans = {
    localeChangeInterceptor(your.package.CustomLocaleChangeInterceptor) {
        paramName = "lang"
    }
}
Run Code Online (Sandbox Code Playgroud)

GIST
的想法是覆盖默认值localeChangeInterceptor,这是i18n grails插件中的默认拦截器,以便处理请求url参数中的带连字符的语言环境字符串.在自定义语言环境拦截器中查看的主要逻辑是:

try {
        // choose first if multiple specified
        if (localeParam.getClass().isArray()) {
            localeParam = ((Object[])localeParam)[0]
        }

        //If locale hyphenated, then change to underscore
        if(localeParam.toString()?.contains('-')){
            localeParam = StringUtils.replace(localeParam.toString(), "-", "_")
        }

        def localeResolver = RequestContextUtils.getLocaleResolver(request)
        def localeEditor = new LocaleEditor()
        localeEditor.setAsText localeParam.toString()
        localeResolver?.setLocale request, response, (Locale)localeEditor.value
        return true
    }
    catch (Exception e) {
        return true
    }
Run Code Online (Sandbox Code Playgroud)