We are using Spring Boot for the application. In ApplicationConfig.java I have the below code
@Bean
public LocaleResolver localeResolver() {
return new SmartLocaleResolver();
}
and the SmartLocaleResolver.java is below
public class SmartLocaleResolver extends SessionLocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
final String acceptLanguage = request.getHeader("Accept-Language");
if (acceptLanguage.contains(",")) {
String[] aheader = acceptLanguage.split(",[ ]*");
for (String locale : aheader) {
if (ApplicationConstants.LOCALE.contains(locale)) {
locale.trim();
return Locale.forLanguageTag(locale);
}
}
} else if (!acceptLanguage.contains(",") && !acceptLanguage.isEmpty()) {
if (ApplicationConstants.LOCALE.contains(acceptLanguage)) {
return Locale.forLanguageTag(acceptLanguage);
}
}
return request.getLocale();
}
}
and I have in my constants class the below to compare the value from header Accept-Language.
public static final List LOCALE = Collections .unmodifiableList(Arrays.asList("en", "es"));
I know in actual scenario the header will be like Accept-Language : fr,es;q=0.8,en-us;q=0.6 but for testing purpose i'm passing it as below.
Accept-language : fr,es,en
The code is not complete yet, but i'm just testing from postman to see if the code picks up "es" as the locale and gives me the localized result.
I don't have messages_fr.properties file but I have messages_es.properties so I expect if the application sets the locale from the below code, it would pick Locale as 'es' and give the values I want in Spanish. What changes I need to make here for the code to work?
The solution is:
instead of
Below is the updated code:
and in my constants class I have: