Grails i18n: Store user’s locale in DB

with No Comments

Sometimes you need to store user’s locale in a DB. Grails uses Spring LocaleResolver eg CookieLocaleResolver, SessionLocaleResolver etc. So for creating CustomLocaleResolver you need to implemets Spring LocaleResolver interface.

Firstly, add the locale field to the User domain.

Then, create CustomLocaleResolver.

Loading a user’s locale from DB every time it is needed does not seem to be a good idea, so one should load a user locale once and store it in a session. Class CustomLocaleResolver extends spring SessionLocaleResolver, so you need to override resolveLocale method only. Method determineDefaultLocale(request) returns the specified default locale, if any, else falls back to the request’s accept-header locale. Don’t forget to put a locale to session. Usually an app allows several locales only, so you can add a method which checks a user’s locale and sets a default locale if user’s locale is not allowed.

Also add a locale selector on UI and add a handler method.

Finally, override default LocaleResolver. Put it to grails-app/conf/spring/resources.groovy.

Leave a Reply