2017-08-17 35 views
1

我想让i18n与我的春季启动应用程序一起使用,它使用thymeleaf作为模板引擎。i18n(国际化)和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 /主/资源)我做了文件夹国际化和里面我把messages.propertiesmessages_sl.properties

内限定有first.greeting =世界您好!

这是我thymeleaf模板:

<!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 

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

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

这里是我的项目结构:

project structure

回答

3

添加classpath:前缀MessageSource's基名

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