【问题标题】:Grails - Change locale behavior to use dash instead of underscoreGrails - 更改语言环境行为以使用破折号而不是下划线
【发布时间】:2013-09-15 10:36:03
【问题描述】:

我正在编写一个 Grails 应用程序,它可以像这样从第 3 方获取它的语言环境:

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

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

有更好的方法吗?

【问题讨论】:

    标签: grails web internationalization request locale


    【解决方案1】:

    覆盖默认行为的一种方法是将CustomLocaleChangeInterceptor注册为resources.groovy中的bean

    beans = {
        localeChangeInterceptor(your.package.CustomLocaleChangeInterceptor) {
            paramName = "lang"
        }
    }
    

    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
        }
    

    【讨论】:

      【解决方案2】:

      我认为您可以在 /grails-app/conf 中添加自己的过滤器,例如:

      class LocaleFixingFilters {
      
          def filters = {
              trace(controller:'*', action:'*') {
                  before = {
                      params.lang = params.lang?.replaceAll('-', '_')
                  }
              }
          }
      }
      

      【讨论】:

      • 感谢您的回复,但是过滤器在错误后被调用(+1 表示努力):)
      • 很奇怪,因为它确实对我有用,但可能取决于所有“之前”拦截器的执行顺序
      • 这是我得到的错误:“拦截语言环境更改时出错:语言环境部分“de-DE”包含无效字符”
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      相关资源
      最近更新 更多