How can I force Grails to use only one language?

荒凉一梦 提交于 2019-12-31 20:03:15

问题


I want to make my Grails application support only one language, that I can define somewhere, completely ignoring the client's headers or the "lang" parameter. Is there any way I can do so? Thanks.


回答1:


Define a LocaleResolver bean in your config/spring/resources.groovy to set the default locale.

beans = {
   localeResolver(org.springframework.web.servlet.i18n.SessionLocaleResolver) {
      defaultLocale = new Locale("de","DE")
      java.util.Locale.setDefault(defaultLocale)
   }
}

This is useful if you don't have to deal with the lang parameter - otherwise it would get overridden. To even ignore the lang parameter value you can set the locale in a Filter upon each request:

import org.springframework.web.servlet.support.RequestContextUtils as RCU
...
def filters = {
    all(controller:'*', action:'*') {

        before = {
            def locale = new Locale("sv","SV")
            RCU.getLocaleResolver(request).setLocale(request, response, locale)                  
        }

    }
}

This approach seems a bit repetitive as Locale is re-set on every request. It would be more elegant to disable the browsers locale detection via an config option.




回答2:


remove all messages_xx.properties files and keep only the messages.properties files. This is the default message bundle to which the system will always fall back if it can't find the right message bundle.

This way you can still use messages (and thus keep the option to nationalize your app) but users will get always the same language.




回答3:


The default LocaleResolver of Grails is SessionLocaleResolver. If you want to always use de_DE you can change this to FixedLocaleResolver.

beans {
  localeResolver(FixedLocaleResolver) {
      locale = new Locale("de", "DE")
  }
}

If you want to restrict to a set of locales, then you will need a filter, and use the SessionLocaleResolver#setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) method.




回答4:


This worked for me in order to override the default localResolver bean

beans = {
    localeResolver(org.springframework.web.servlet.i18n.FixedLocaleResolver) {
        setLocale(Locale.US)
    }
}


来源:https://stackoverflow.com/questions/8808188/how-can-i-force-grails-to-use-only-one-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!