How do I force Spring Boot to use a default locale when it can't find the message key in the user's given locale? I found this guide: https://www.baeldung.com/spring-boot-internationalization
I have the following:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public LocaleResolver localeResolver() {
AcceptHeaderLocaleResolver lr = new AcceptHeaderLocaleResolver();
lr.setDefaultLocale(Locale.ENGLISH);
return lr;
}
I have messages_es.properties
, messages_en.properties
(and many more).
I have the key oops-theme
in messages_en.properties
, but it is absent from all the other messages*.properties
.
I set my browser to Accept-Language: es-ES,es;q=0.9,en-US;q=0.8,en;q=0.7
.
Yet, when I access a JSP page with the oops-theme
, it gives the exception
javax.servlet.jsp.JspTagException: No message found under code 'oops-theme' for locale 'es_ES'.
The JSP contains
<spring:message code="oops-theme"/>
How do I use a default locale for looking up messages when Spring Boot can't find them in the given locale?
Spring Boot 1.5.21.
Fill messages.properties
with the messages for the fall-back text, e.g. in English.
Then don't write messages_en.properties
, since the default messages are already in English.
Note that this is entirely independent of the setDefaultLocale(Locale.ENGLISH)
, as that simply states which Locale to use if the Accept-Language header is missing.
Example: You can write messages.properties
in German, if you want, then have a messages_en.properties
for English, and messages_es.properties
for Spanish. You can then have setDefaultLocale(Locale.SPANISH)
, which means that if the browser doesn't specify a locale, you get Spanish, but for every message where a Spanish text hasn't been provided in messages_es.properties
, you'd get the default German text from messages.properties
.
You should read the javadoc of ResourceBundle
and the PropertyResourceBundle
subclass to learn how this all works.