Retrieve active locale in Grails application

拜拜、爱过 提交于 2019-12-17 23:43:05

问题


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"


回答1:


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)



回答2:


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




回答3:


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

import org.springframework.context.i18n.LocaleContextHolder;

LocaleContextHolder.getLocale();



回答4:


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=


来源:https://stackoverflow.com/questions/7245004/retrieve-active-locale-in-grails-application

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