我正在尝试使用 Spring Boot 和 Thymeleaf 创建一个 Web 应用程序,但在让模板使用属性文件中定义的消息时遇到问题。它不是显示属性文件中定义的消息,而是显示 ??form.welcome_en_GB??
控制台未记录任何错误。
项目结构是这样的
──┬ 🗁 src
│ └─── 🗁 main
│ ├─── 🗁 java
│ │ └─── 🗁 com
│ │ └─── 🗁 package
│ │ ├─── 🗁 controller
│ │ │ └─── FormController.java
│ │ ├─── Application.java
│ │ └─── ServletInitializer.java
│ └─── 🗁 resources
│ ├─── 🗁 static
│ │ └─── home.html
│ ├─── 🗁 templates
│ │ ├─── form.html
│ │ └─── form.properties
│ └─── application.properties
└─── pom.xml
应用程序.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
ServletInitializer.java
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
FormController.java
@Controller
@RequestMapping("/form")
public class FormController {
private static final Logger log = LoggerFactory.getLogger(FormController.class);
@RequestMapping(value = "/new", method = RequestMethod.GET)
public ModelAndView getNewReportForm() {
log.info("New form requested");
ModelAndView mav = new ModelAndView("form");
return mav;
}
}
表单.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" media="all"/>
</head>
<body>
<p th:text="#{form.welcome}">Welcome!</p>
</body>
</html>
表单属性
form.welcome=Hello there!
最佳答案
我相信将 form.properties
的名称更改为 messages.properties
并将其放置在资源文件夹的根目录中应该允许 Spring Boot 自动拾取它.
当我有多个消息文件时,我会在 MessageSource bean 中显式列出它们,以便 MVC 自动配置选取它们,例如:
@Bean
public MessageSource messageSource() {
final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:/some-mvc-messages", "classpath:/some-other-mvc-messages", "classpath:/another-projects/mvc-messages");
messageSource.setUseCodeAsDefaultMessage(true);
messageSource.setDefaultEncoding("UTF-8");
messageSource.setCacheSeconds(5);
return messageSource;
}
关于Spring Boot + Thymeleaf 找不到消息属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36545667/