Spring MVC - Customized Locale selection using CookieLocaleResolver

[Last Updated: Feb 25, 2017]

This is another option to remember a customized locale selection.


CookieLocaleResolver internally persists a custom locale and/or a time zone information as browser cookie. It uses javax.servlet.http.Cookie to accomplish that. This LocaleResolver is preferred to be used (over SessionLocaleResolver), when application has to be stateless or when locale information should be persisted beyond HTTPSession life time.

Like we discussed in SessionLocaleResolver example, there might be many different scenarios where a Locale instance should be remembered on the server side. Here we are going to use the same scenarios as of the last example, where ChangeLocaleInterceptor will retrieve the specified HTTP param value, parse it to the Locale instance and then will hand over it to the underlying LocaleResolver (CookieLocaleResolver in this case). The CookieLocaleResolver at this point will add the locale information as a Cookie to HTTP response.

Registering CookieLocaleResolver

public class Main {

    public static void main (String[] args) {, args);

    public LocaleResolver localeResolver () {
        CookieLocaleResolver r = new CookieLocaleResolver();

        //if set to -1, the cookie is deleted
        // when browser shuts down
        return r;

    public WebMvcConfigurer configurer () {
        return new WebMvcConfigurerAdapter() {
            public void addInterceptors (InterceptorRegistry registry) {
                LocaleChangeInterceptor l = new LocaleChangeInterceptor();

The rest of the artifacts remain the same as of the last example. The output and flow is also same.

After changing the language in the dropdown, a cookie will be created in the browser.

In google chrome browser (right click on page > Inspect > Application (top toolbar) > Storage (left tree) > Cookies > http://localhost:8080):

Example Project

Dependencies and Technologies Used:

  • Spring Boot 1.4.3.RELEASE
    Corresponding Spring Version 4.3.5.RELEASE
  • spring-boot-starter-web : Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
  • tomcat-embed-jasper 8.5.6: Core Tomcat implementation.
  • JDK 1.8
  • Maven 3.3.9

Cookie Locale Resolver Example Select All Download
  • cookie-locale-resolver-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
          • resources
            • msgs
          • webapp
            • WEB-INF
              • pages

    See Also