Wednesday, August 16, 2006

Java Spring and Locales

Related to my previous post. We were updating a web app and localizing it for some new countries.

The jsps used some Spring tag libs.

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />

Spring comes with an inbuilt LocaleResolver. By default it uses the AcceptHeaderLocaleResolver which detects the clients Locale from the Http headers (which are sent with the bowsers request).

In our case we didn't want the client locale to get picket up. We wanted to set it based on the servername. (To do these we added some virtual hosts to our tomcat instance).

Then to update the Spring Locale we had to use the SessionLocaleResolver . This has to be instantiated via the Spring xml file (otherwise it will default to AceptHeaderLocaleResolver).

We then simply set the Locale froma filter.

String servername = httpRequest.getServerName();
Locale locale = null;
if(servername.indexOf("")>0){"Setting UK locale");
locale = Locale.UK;
}else if(servername.indexOf(".fr")>0){"Setting FR locale");
locale = Locale.FRANCE;
}else if(servername.indexOf(".de")>0){"Setting DE locale");
locale = Locale.GERMANY;
}else{"Cannot ascertain originating server. Defaulting to UK locale");
locale = Locale.UK;

No comments: