REST services with Spring – getting the client locale

Stories about project management and coding

REST services with Spring – getting the client locale

When building a REST backend, you often need to know what language the user is using.

This is why the HTTP/1.1 standard (section 14.4) defines the Accept-Language header. Most HTTP clients (web browsers at least) set this header to the language the user has set as his system language.

Getting this header property in Java backend can be a bit inconvenient, at the very least it can lead to rather unreadable code.
The worst example if ever seen looked like this:

See how much code this is for such a little thing? Also it’s quite unsafe, for example, it does not check if the AcceptHeader contains garbage (could lead to an IllformedLocaleException).

Here’s a version I’ve been using for a long time:

A bit shorter, makes use of a null-return if the framework could not map a request locale – less code for use – yay.

Today a came across a completely different method in an util class, it makes use of Springs RequestContextHolder:

The try-/catch is a little lazy, with just catching every possible exception, but it will work nonetheless.
Now you can just use UtilClass.getClientLocale(), short and simple.

PS: Sure you could’ve just put the above code in the first two examples in another helper method, but that wasn’t my point 😀

Tags: , , ,

Leave a Reply

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