gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:47:35 24 4
gpt4 key购买 nike

我正在尝试让 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!

这是我的 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>

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

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

但是,当我加载页面时,我得到的不是 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

最佳答案

classpath: 前缀添加到 MessageSource 的 basename

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

关于java - 带有 i18n(国际化)和 thymeleaf 的 Spring Boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45742820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com