Spring Boot - Localize requests arriving at custom (DWR) AbstractController, localize child threads, LocaleResolver vs. LocaleChangeInterceptor

181 views Asked by At

So I've been meddling with this subject for quite some time now, trying to understand the best available solution for localizing a Spring Boot project. My use case is as follows: The locale should be resolved according to a DB saved (and later cached) user preferences, which when absent defaults to the browser locale, which when absent defaults to global system locale. Also, I should support child thread localization.

To top it all my project is using the legacy DWR technology, so most of the requests to the server pass through the DWR controller.

My current solution is implementing the SessionLocaleResolver class, which as I understand its resolveLocale method should be called for each request, where as its return value is what will be returned afterwards anywhere in the code when calling LocaleContextHolder.getLocale(). My work on resolveLocale is quite convulated (goes to DB, cache, and utalizes a series of fallbacks when necessary), but in the end it simply returns a locale.

  • A few questions:
  1. The locale resolver seems to work fine when client requests for static server rendered pages, resolving the correct locale and thus inputs correct translations into the Thymeleaf HTML pages. However requests passing through the DWR Controller (which is basically an extension of AbstractControler) do not invoke the resolveLocale method and thus are not localized properly. I haven't found anywhere in the documentation why this is happening. My current solution is to manually call LocaleContextHolder.setLocale() for every request passing through this controller, but I'm wondering if there's some better solution.

  2. What is the need for the LocaleChangeInterceptor, as opposed to the locale resolver? In all of the tutorials I've seen people use them in conjunction (where for some reason the locale resolver always returns some hard coded locale, like Locale.US, and the interceptor is doing the heavy lifting). I avoided using it as it seems the practice here is scooping the locale from the request header, while my use case is a bit different.

  3. What is the best practice for localizing child threads of the current request thread? I know of using LocaleContextHolder.setLocale(locale, true) for localizing spawned threads, but [a] If I'm not careful and forget reverting the child thread locale to the original when the task is done I might have the same thread handling some task initiated by a thread of different locale (by some other user), mixing langauges. [b] How do we perform the equivalent of LocaleContextHolder.setLocale(locale, true) via the built in locale resolver? I haven't found it anywhere.

Thank you!

0

There are 0 answers