August 27, 2010

Providing GWT with the browser's locale at runtime

I think it's my first post on GWT (Google Web Kit) so bear with me, I come in peace :).
I came across a problem where I've created a localization support for a project but wanted my generated code to obtain the browser's locale (note: not the system locale) and act accordingly on runtime.
Now GWT supplies 2 formal way on setting the locale for the web page; one is with a query string on the URL request and the other is adding the metadata on the host page and set the GWT property.
Both option are not satisfying since the a simple HTML cannot access the browser locales (security issues as far as I've looked), so the web pages cannot obtain the locale. You can use GWT to fetch the locale and reload the page with the right locale concatenated to the URL, but that will cause the page to flicker… nhaaaa, not good enough.
The solution is rather simple - having the server analyze the http request and get the browser's locale from it. You don't want you page to flicker, but rather generate the metadata on the host page which holds the locale information for GWT.
Comes JSP.
Since the project runs on J2EE application server, I was able to create a simple JSP page, to be used as the host page for GWT, and have a code inside that will generate the metadata for the locale derived from the request.
Here is the code
<meta name="gwt:property" content="locale=<%= request.getLocale()%>">


Hope this help you guys, I spent some time searching for an elegant solution on the web but couldn't find anything specific, so there you go.


guya said...

Going to the server for this king of info is OK, but you can use javascript as well.

Did some quick tests and found these are working just fine:
Chrome & FireFox

Flashmattic said...

Didn't work for me with IE8 and FF. when I changed the preferred locales, the application did not receive the locale token... weird.
I'll give it another shot.
BTW, I'm not "going to the server. the JSP translates into a servlet running on the server.