【问题标题】:Spring boot with i18n (internationalization) and thymeleaf带有 i18n(国际化)和 thymeleaf 的 Spring Boot
【发布时间】:2018-01-26 07:46:30
【问题描述】:

我正在尝试让 i18n 与我的 Spring Boot 应用程序一起工作,该应用程序使用 thymeleaf 作为模板引擎。

我遵循了一些教程,这些教程向我展示了如何定义消息源和语言环境解析器,因此我制作了这个配置类:

@Configuration
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter {

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource msgSrc = new ReloadableResourceBundleMessageSource();
        msgSrc.setBasename("i18n/messages");
        msgSrc.setDefaultEncoding("UTF-8");
        return msgSrc;
    }

    @Bean
    public LocaleResolver localeResolver() {
        CookieLocaleResolver resolver = new CookieLocaleResolver();
        resolver.setDefaultLocale(new Locale("en"));
        resolver.setCookieName("myI18N_cookie");
        return resolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry reg) {
        LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
        interceptor.setParamName("locale");
        reg.addInterceptor(interceptor);
    }

}

然后,在我的资源文件夹 (src/main/resources) 中,我创建了文件夹 i18n 并在里面放了 messages.propertiesmessages_sl.properties强>

里面定义了first.greeting = Hello World!

这是我的百里香模板:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" th:with="lang=${#locale.language}" th:lang="${lang}">
    <head>
        <meta charset="UTF-8"/>
    </head>
    <body>
        <a href="/?locale=en">English</a> | <a href="/?locale=sl">Slovenian</a>
        <h3 th:text="#{first.greeting}"></h3>
    </body>
</html>

我的控制器没什么特别的,它只是在我访问它时转发这个视图,并且在我定义的属性文件中:

spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.cache=false

但是,当我加载页面时,我得到的是 ??first.greeting_en????first.greeting_sl?? 而不是 Hello World! /strong>,取决于设置的语言环境。

我到处都看到了相同的配置,所以我真的迷失了,因为我错过了什么。

这是我的项目结构:

???? src
   └─── ???? main
       ├─── ???? java
       │   └─── ???? com
       │       └─── ???? mjamsek
       │           └─── ???? Simple_i18n
       │               ├─── ???? conf
       │               └─── ???? controller
       └─── ???? resources
           ├─── ???? i18n
           │   ├─── messages.properties
           │   └─── messages_sl.properties
           ├─── ???? static
           └─── ???? templates

【问题讨论】:

    标签: java spring spring-mvc internationalization thymeleaf


    【解决方案1】:

    classpath: 前缀添加到MessageSource's 基本名称

    msgSrc.setBasename("classpath:i18n/messages");
    

    【讨论】: