Java applications: Get supported Locale

For web application developers, internationalization of the application is an absolute neccesity. The user should be able to select a locale that suits him from a supported set of locales. What locale is appropriate when the locale has not already been selected? One solution is to fall back on a default locale, provided it is supported by the users browser.

I found a small, useful snippet of code on Koders.com. The application checks to see if it can match up any of the locales supported by the Browser to the locales that it can support. For those unfamiliar with Java, understanding the underlying concepts is easy. These concepts are really language-independent and are good to know if your interested in web services. For intermediate level web developers, this is probably a concept encountered and learnt often.

The key idea is a simple one. Java Locales are a combination of language and country. While there exist different locales for “English, US” and “English, UK”; a web application will often support just the English language in an answer to both locales. However, Browsers will explicitly list “English, US” (or UK as the case may be). A strict match between “English”, and “English, US” will fail (see Locale.equals()). Instead, applications must treat the supported language – “English”, as a wildcard, matching it with “English, US”, when appropriate.

Be wary of the pitfalls in this approach. You can get away with showing “English, US” to users from UK. You might now get away with showing a page rendered in “Chinese, PRC” to users from Taiwan. I’m not sure if this example is the best one, but it illustrates the problem. To summarise, the application may be written treat the supported locale “English” as a wildcard. On the other hand, when explicitly told to support “English, US” it should resort to strict matching of locales to locales supported by the browser.

You can also enhance the scheme by matching Brand’s default locale before looking at other locales.

Resources.