Saturday, July 2, 2011

GWT internationalization and cookies

Today I wanted to setup internationalization for a project I'm working on. I decided for various reasons not to use the ?locale=x_y but to use a cookie to allow the user to set the locale, and for the site to remember the users preference. I spend some time trying to figure out how to do this right in GWT, using no additional libraries and avoiding any changes to the GWT generated HTML.

Here is what I came up with:

In my <project>.gwt.xml file I added the following line:
<set-configuration-property name="locale.cookie" value="gwtLocale"/>

On the page I created a simple dropdown box with all the languages supported by my site. I am filling this box with the following code (shamlessly coppied from the GWT Showcase app by Google).
     String[] localeNames = LocaleInfo.getAvailableLocaleNames();
for (String localeName : localeNames) {
if (!localeName.equals("default")) {
String nativeName = LocaleInfo.getLocaleNativeDisplayName(localeName);
languageBox.addItem(nativeName, localeName);
if (localeName.equals(currentLocale)) {
languageBox.setSelectedIndex(languageBox.getItemCount() - 1);
In the change handler for this dropdown box I set up the following bit of code:

  String localeName = languageBox.getValue( languageBox.getSelectedIndex() );

Date now = new Date();
long nowLong = now.getTime();
nowLong = nowLong + (1000 * 60 * 60 * 24 * 21);
Cookies.setCookie("gwtLocale", localeName, now);

Then once the page is reloaded I do the following:
  String currentLocale = Cookies.getCookie( LocaleInfo.getLocaleCookieName() );

if (currentLocale.equals("default") || currentLocale == null ) {
currentLocale = "en_US";
And that's it a very simple clean and easy pure GWT way of allowing your user to set their locale for your website using a cookie. Not bad for my first day of playing wit GWT, now on to the next task of the project having a user login on the site. (Authentication only for now Authorization will follow after that...)

No comments:

Post a Comment