Finding User’s Session Locale in GSP

14 / Jul / 2010 by Abhishek Tejpaul 4 comments

There are situations where you might want to know the Locale of the user as set in the session in your GSP so that you can show text in a particular language/manner. Here the Spring framework’s SessionLocaleResolver can come to the rescue. In one of our recent Grails projects, we did the following in one of our GSPs to display the content accordingly.

Please note that our use-case was like that in which we have fields for different languages in our domain classes. For example:

class MyDomain {
String greetingEnglish
String greetingFrench

And now you have to conditionally display the object’s fields based on the user’s locale. If this were a static text, then the Grails in-built i18n support in the form of message bundles would be the ideal solution. But this is a different scenario.

So let’s start by writing the following in your GSP :

The above statement returns the ISO Language Code from the session object which is a map. In Grails, the map values can be retrieved by the ‘.’ operator too by passing the keys. These codes are the lower-case, two-letter codes as defined by ISO-639. For example: ‘en’ for English, ‘fr’ for French and so on.

Once you know the locale, you can show the conditional content on your page. It could be something like this:



Default Greeting

Hope this will help !!!

– Abhishek Tejpaul

[Intelligrape Software Pvt. Ltd.]


comments (4)

  1. Laura

    Thanks!! I need to know de locale in order to use a jQuery plugin and I couldn’t find how to get it in my view!

  2. S Vivek Krishna

    Hi Abhishek,

    Another way to do this(and probably a better way because the GSP would be cleaner) is to put the texts in individual message.properties_ files and use the message code to display the text inside the GSP.



    1. abhishek

      Hello Vivek,

      Thanks for leaving the comment. But I had a different scenario here; and I have updated the blog accordingly which now explains our use-case.

      – Abhishek


Leave a Reply

Your email address will not be published. Required fields are marked *