当缺少消息密钥时,如何使 Spring 引导默认为语言环境?

How do you make Spring Boot default to a locale when a message key is missing?

当无法在用户给定的语言环境中找到消息密钥时,如何强制 Spring Boot 使用默认语言环境?我找到了这个指南: https://www.baeldung.com/spring-boot-internationalization

我有以下内容:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Bean
    public LocaleResolver localeResolver() {
        AcceptHeaderLocaleResolver lr = new AcceptHeaderLocaleResolver();
        lr.setDefaultLocale(Locale.ENGLISH);
        return lr;
    }

我有 messages_es.propertiesmessages_en.properties(以及更多)。

我在 messages_en.properties 中有密钥 oops-theme,但在所有其他 messages*.properties 中都没有。

我将浏览器设置为 Accept-Language: es-ES,es;q=0.9,en-US;q=0.8,en;q=0.7

然而,当我使用 oops-theme 访问 JSP 页面时,它给出了异常

javax.servlet.jsp.JspTagException: No message found under code 'oops-theme' for locale 'es_ES'.

JSP 包含

<spring:message code="oops-theme"/>

当 Spring Boot 在给定的语言环境中找不到消息时,如何使用默认语言环境查找消息?

Spring 引导 1.5.21.

用 fall-back 文本的消息填充 messages.properties,例如英语。

那就不要写messages_en.properties,因为默认消息已经是英文了。

请注意,这完全独立于 setDefaultLocale(Locale.ENGLISH),因为它只是说明了如果 Accept-Language header 缺失时要使用的语言环境。

示例: 如果需要,您可以用德语写 messages.properties,然后用 messages_en.properties 表示英文,messages_es.properties西班牙语。然后您可以使用 setDefaultLocale(Locale.SPANISH),这意味着如果浏览器未指定语言环境,您将获得西班牙语,但是对于在 messages_es.properties 中未提供西班牙语文本的每条消息,您将从 messages.properties.

获取默认德语文本

您应该阅读 ResourceBundle and the PropertyResourceBundle 子类的 javadoc 以了解这一切是如何工作的。