Close

Spring MVC - CookieLocaleResolver Examples

[Last Updated: Nov 8, 2025]

Spring MVC 

CookieLocaleResolver uses browser cookie to store a custom locale instance.

package com.logicbig.example;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import java.time.Duration;
import java.util.Locale;

@EnableWebMvc
@Configuration
@ComponentScan
public class WebConfig implements WebMvcConfigurer {

@Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver r =
new CookieLocaleResolver("localInfo");
r.setDefaultLocale(Locale.US);
r.setCookieMaxAge(Duration.ofDays(1));
return r;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor l = new LocaleChangeInterceptor();
l.setParamName("localeCode");
registry.addInterceptor(l);
}

@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/pages/", ".jsp");
}

@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasenames("msgs/msg");
source.setDefaultEncoding("UTF-8");
return source;
}
}
Original Post




See Also

Join