Chain of Spring CookieLocaleResolver and AcceptHeaderLocaleResolver

I want to first localize the user's locale by detecting a cookie, and if not, then the accept-language header. Spring seems to want to accept only one LocaleResolver .

Interestingly, Spring docs for CookieLocaleResolver state

An implementation of LocaleResolver that uses a cookie sent to the user in the case of a user preference, deviating from the default value of the locale or locale of the request-header request.

But actually it is not. testing shows that this does not work, and a quick look at the source shows that it gets the default value if there is no cookie.

Is the only solution for writing my own implementation of LocaleResolver ?

+7
source share
2 answers

It looks like CookieLocaleResolver does exactly what you want until you set its defaultLocale .

If you need something else (for example, returning to defaultLocale when no cookie or Accept ), you can modify its determineDefaultLocale() accordingly.

+9
source

An example of a cookie locale regenerator that first returns to the Accept-Language header, and then defaultLocale :

 public class CookieThenAcceptHeaderLocaleResolver extends CookieLocaleResolver { @Override protected Locale determineDefaultLocale(HttpServletRequest request) { String acceptLanguage = request.getHeader("Accept-Language"); if (acceptLanguage == null || acceptLanguage.trim().isEmpty()) { return super.determineDefaultLocale(request); } return request.getLocale(); } } 
+3
source

All Articles