How does Spring MVC use LocaleResolver?

LocaleResolver is the Spring MVC abstraction responsible for determining which Locale to use for a given request, driving internationalization across the application. It decides the current locale based on a configurable strategy and makes that locale available for message resolution and formatting.

Key Points: • AcceptHeaderLocaleResolver derives the locale from the browser's Accept-Language header, requiring no extra state. • SessionLocaleResolver stores the resolved locale in the HTTP session, so it persists across requests for that user's session. • CookieLocaleResolver stores the locale in a cookie, persisting it across sessions and even browser restarts. • Once resolved, the locale drives Spring's MessageSource for translated text and also affects date, number, and currency formatting throughout the request. • A LocaleChangeInterceptor is commonly paired with a LocaleResolver to let users explicitly switch languages via a request parameter.

Example: An app using CookieLocaleResolver remembers a user selected Spanish even after they close and reopen the browser, rendering all message-bundle text and formatted dates in Spanish on their next visit without asking again.

Code Example:

@Bean
public LocaleResolver localeResolver() {
    CookieLocaleResolver resolver = new CookieLocaleResolver();
    resolver.setDefaultLocale(Locale.US);
    resolver.setCookieMaxAge(Duration.ofDays(30));
    return resolver;
}

Interview Tip: A concise interview answer is:

"LocaleResolver determines which locale applies to a request, and Spring offers several strategies — AcceptHeaderLocaleResolver reading the browser header, or SessionLocaleResolver and CookieLocaleResolver persisting an explicit choice across requests or sessions. Once resolved, that locale drives message translation and date/number formatting throughout the request."