15

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?

Qwerky
  • 18,217
  • 6
  • 44
  • 80

2 Answers2

13

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.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
axtavt
  • 239,438
  • 41
  • 511
  • 482
  • Thanks, this seems to work. Maybe I just misunderstood the docs, it could be a little clearer. – Qwerky Dec 01 '11 at 13:39
9

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();
    }
}
user11153
  • 8,536
  • 5
  • 47
  • 50