I want to resolve the user's locale first by detecting a cookie, and if there isn't one then by the accept-language header. Spring seems to only want to accept a single LocaleResolver
.
Interestingly, the spring docs for CookieLocaleResolver
state
LocaleResolver implementation that uses a cookie sent back to the user in case of a custom setting, with a fallback to the specified default locale or the request's accept-header locale.
but this doesn't actually seem to be the case; testing shows it doesn't work and a quick look at the source shows it only gets the default if there is no cookie.
Is the only solution to write my own LocaleResolver
implementation?
Example cookie locale resolver that fallback first to Accept-Language
header and only then to 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();
}
}
It looks like CookieLocaleResolver
does exactly what you want as long as you don't set its defaultLocale
.
If you want something different (for example, fallback to defaultLocale
when neither cookie nor Accept
header was found), you can override its determineDefaultLocale()
accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With