如何使用thymelaf在Spring中的外部化消息之间切换



弹簧+thymelaf

我想根据需要显示来自Messages_pl.propertiesMessages_en.properties的消息。这是我的问题,因为当我想查看第二个文件中的消息时,我不知道该怎么办(默认情况下会考虑Messages_pl.properties(。

为了使用指定的basename访问资源包,我将下面的bean添加到我的@Configuration类:

@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("Messages");
return messageSource;
}

Messages_pl.properties:

welcome.message=siemanko

Messages_en.properties:

welcome.message=hello

我使用这个属性的html文件的片段:

<h1 th:text="#{message.welcome}"></h1>

结果:siemanko

我应该怎么做才能得到hello的结果?

您可以在同一个文件Messages.properties上定义以下内容:

welcome.message.pl=siemanko
welcome.message.en=hello

然后,您可以使用本地解析器使您的项目能够确定当前使用的区域设置:

@Bean
public LocaleResolver localeResolver() {
return new CookieLocaleResolver();
}

然后添加您的语言的拦截器:

@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
registry.addInterceptor(localeChangeInterceptor);
}

之后,在语言之间切换很简单,您只需更改链接上参数lang的值:

localhost:8080/your_page?lang=pl // will show siemanko on your page
localhost:8080/your_page?lang=en // will show hello on your page

最新更新