CQ 5.5 i18n and accept-lanugage header
adobe, aem, internationalization, java, servlets
Solution
CQ/Sling (as of 5.6) does not read the Accept-Language header for the locale you get via `slingRequest.getLocale()` (or `slingRequest.getResourceBundle(null)` which implicitly uses that locale), instead it uses the user's language setting (`~/preferences/@language` in the JCR) or a configurable default (1).
The reasoning is that a fixed setting is much stabler, also when using different browsers across devices, than guessing the language header.
But it's extensible: you can hook in a custom org.apache.sling.i18n.RequestLocaleResolver service (with a higher service rank), which is the service that provides the value for `slingRequest.getLocale()` (2). This could also take the accept language into account; it gets access to the underlying servlet request object, which should give you the Accept-Language header value in `getLocale()` and `getLocales()` (at least the built-in servlet engine in CQ does that since 5.4).
(1) Configure default locale on this service: `http://localhost:4502/system/console/configMgr/org.apache.sling.i18n.impl.JcrResourceBundleProvider`
(2) Sling's `I18nFilter` which you probably have seen in stack traces already does all the magic and wraps the request to provide the `slingRequest.getLocale()` and `slingRequest.getResourceBundle()` implementations using the `RequestLocaleResolver` and `ResourceBundleProvider` services
Problem
I try to use i18n localization but I have stuck. If I use: ``` I18n i18n = new I18n(slingRequest); i18n.get("myMessage"); ``` I always get the english message for key: myMessage. In accept-language header I can see these values: de,en;q=0.5 but: request.getLocale() returns: en request.getLocales() returns: en If I use code below everything is good: ``` Locale myLocale = new Locale("de"); ResourceBundle resourceBundle = slingRequest.getResourceBundle(myLocale); I18n i18n = new I18n(resourceBundle); ``` Why don't cq read "accept-language" request headers? ps: I use standalone cq jar... Thanks in advance!