Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining Spring CookieLocaleResolver and AcceptHeaderLocaleResolver

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?

like image 233
Qwerky Avatar asked Dec 01 '11 13:12

Qwerky


2 Answers

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();
    }
}
like image 60
user11153 Avatar answered Oct 15 '22 10:10

user11153


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.

like image 12
axtavt Avatar answered Oct 15 '22 08:10

axtavt