带有 i18n(国际化)和 thymeleaf 的 Spring Boot

Mih*_*sek 4 java spring spring-mvc internationalization thymeleaf

我正在尝试让 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);
    }

}
Run Code Online (Sandbox Code Playgroud)

然后,在我的资源文件夹(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>
Run Code Online (Sandbox Code Playgroud)

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

spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.cache=false
Run Code Online (Sandbox Code Playgroud)

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

我看到的每个地方都看到了相同的配置,所以我真的很迷茫,因为我错过了什么。

这是我的项目结构:

 src
   ????  main
       ????  java
       ?   ????  com
       ?       ????  mjamsek
       ?           ????  Simple_i18n
       ?               ????  conf
       ?               ????  controller
       ????  resources
           ????  i18n
           ?   ???? messages.properties
           ?   ???? messages_sl.properties
           ????  static
           ????  templates
Run Code Online (Sandbox Code Playgroud)

isa*_*sah 5

classpath:前缀添加到MessageSource'sbasename

msgSrc.setBasename("classpath:i18n/messages");
Run Code Online (Sandbox Code Playgroud)