Retrieve active locale in Grails application

2019-01-22 19:54发布

I know I can use the "lang" parameter to automatically change the current locale as described in the docs, but how do I track those changes, for example to update the language stored in the current user domain object?

request.locale does not work, since it does not reflect the changes done via "?lang=xx"

4条回答
啃猪蹄的小仙女
2楼-- · 2019-01-22 20:18

Within your controller you can obtain the locale using the RequestContextUtils.

import org.springframework.web.servlet.support.RequestContextUtils as RCU

Then to resolve the locale for the request:

RCU.getLocale(request)
查看更多
虎瘦雄心在
3楼-- · 2019-01-22 20:25

Grails uses Spring internally. You can get the current locale from Spring's RequestContextUtils: http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/servlet/support/RequestContextUtils.html#getLocale(javax.servlet.http.HttpServletRequest)

import org.springframework.web.servlet.support.RequestContextUtils

def locale = RequestContextUtils.getLocale(request)

Check <g:message> tag source for more info:

http://grails.org/doc/latest/ref/Tags/message.html

查看更多
狗以群分
4楼-- · 2019-01-22 20:27

If you display properties of RequestContextUtils.getLocale(request) , you will find the following :

ISO3Country= 
ISO3Language=ara 
displayCountry= 
class=class java.util.Locale 
default=fr_FR 
language=ar 
variant= 
ISOLanguages=[Ljava.lang.String;@4269f8e3 
availableLocales=[Ljava.util.Locale;@3b532125 
displayName=arabe 
ISOCountries=[Ljava.lang.String;@4ea52290 
displayVariant= 
displayLanguage=arabe 
country=
查看更多
爷的心禁止访问
5楼-- · 2019-01-22 20:32

You can also use the LocaleContextHolder which doesn't need a request as a parameter

import org.springframework.context.i18n.LocaleContextHolder;

LocaleContextHolder.getLocale();
查看更多
登录 后发表回答