Spring mvc Spring、Thymeleaf和本地化字符串
我不熟悉使用Spring和Thymeleaf,我不知道把本地化.properties文件放在哪里。我有这个豆子:Spring mvc Spring、Thymeleaf和本地化字符串,spring-mvc,netbeans,thymeleaf,Spring Mvc,Netbeans,Thymeleaf,我不熟悉使用Spring和Thymeleaf,我不知道把本地化.properties文件放在哪里。我有这个豆子: @Bean public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasenames("classpath:me
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:messages/messages", "classpath:messages/validation");
// if true, the key of the message will be displayed if the key is not
// found, instead of throwing a NoSuchMessageException
messageSource.setUseCodeAsDefaultMessage(false);
messageSource.setDefaultEncoding("UTF-8");
// # -1 : never reload, 0 always reload
messageSource.setCacheSeconds(0);
return messageSource;
}
在login.html中:
<p th:text="#{messages.hello}">Welcome to our site!</p>
我的项目结构:
我曾尝试在WEB-INF中创建一个名为messages的文件夹,但显然我做得不对。有什么想法吗
编辑:使用与mesages相关的代码更新问题。此XML中的Basename表示包含不同翻译的.properties
文件的前缀
假设您需要两种语言:英语(en
)和波兰语(pl
)。
您只需将Basename
设置为消息
,如下所示:
messageSource.setBasename("classpath:messages");
然后将两个文件<代码> MasaGeSeE< <代码>和<代码> MasaGeSpL<代码> >在您的代码>类路径< /COD>(<代码> Web-INF应该足够了,尽管考虑使用<代码> SRC/main /Reals< /Cord>目录)。
这是一个基本的例子,应该很容易适应您的情况 我知道这件旧了。但是我已经找到了一个解决方案,并登上了这篇文章。
我自己找到了一个解决方案,其他有同样问题的人可能会来这里 我就是这样解决的: 将
MessageSource
注入SpringTemplateEngineBean
@Bean
public SpringTemplateEngine templateEngine(MessageSource messageSource, ServletContextTemplateResolver templateResolver) {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver);
engine.setMessageSource(messageSource);
return engine;
}
现在Thymeleaf知道了您的
消息源
并计算了您的表达式。您应该将Thymeleaf的SpringTemplateEngine
公开为bean,让Spring将您的消息源
注入其中:
@Bean
public SpringTemplateEngine templateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
有关
MessageSource
配置的信息,请参见MichałRybak的回答。我按照您的建议,在src/main/resources
目录中放置了一个名为messages_en.properties
的文件。但是仍然是标签欢迎访问我们的网站
显示为?消息。您好\u en???
我感觉有些基本的东西正在逃离我。我没有使用Thymeleaf的经验,但没有使用它,我已成功地使用
等显示本地化消息。请包含更多代码,这可能有助于判断错误是在后端还是前端。嗯,这很奇怪。。我使用了
,浏览器上没有显示任何内容。我想做的是和你一起工作。我只是把本地化文件和欢迎来到我们的网站
以及home.html
文件中的
。一定有别的事发生了。。非常感谢您的时间:)正如我之前所说的,我在百里香没有任何经验,所以我不能给您更多的帮助。要在Spring中设置本地化,您需要配置额外的bean-对我来说很有帮助。我建议首先让它与上面的教程一起使用(使用Spring:message标记),然后尝试将它们更改为Thymeleaf的th:text谢谢您的解决方案。遗憾的是,在我发布这个问题后不久,项目就终止了。没有必要设置messageSource
,Spring会自动将messageSource
与SpringTemplateEngine
bean集成。下面是@user882209的答案。
@Bean
public SpringTemplateEngine templateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}