N.B. Прежде чем кто-либо скажет, что это копия из Spring Boot + Thymeleaf, не находящей свойства сообщения , пожалуйста, знайте, что я пытался решить мою проблему, используя ответы, представленные в ссылке, но пока ничего не помогло мне.
У меня проблема с использованием Thymeleaf и Spring Boot. Я следовал учебнику, предоставленному Thymeleaf, но по какой-то причине, когда обработка шаблона закончена, я получаю следующее:
<!DOCTYPE html>
<html>
<body>
<h3>??admin.greeting_en??</h3>
<p>??admin.deposit.request.accepted_en??</p>
<p><strong>??email.generation_en??</strong></p>
<p>??email.regards_en??</p>
<p>??admin.regards_en??</p>
</body>
</html>
Я поместил мои messages_en.properties в модуль, который содержит конфигурацию Spring для Thymeleaf (распознаватель шаблонов, распознаватель сообщений и т. Д.) ... Путь - уведомления / src / main / resources / messages_en.properties
Я также поместил файл свойств в каталог / templates, и он все еще не работает.
Класс установки для тимелина выглядит следующим образом.
@Configuration
public class SpringMailConfig {
@Bean
public MessageSource emailMessageSource() {
final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
@Bean
public TemplateEngine springTemplateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(htmlTemplateResolver());
templateEngine.setTemplateEngineMessageSource(emailMessageSource());
return templateEngine;
}
private ITemplateResolver htmlTemplateResolver() {
final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
templateResolver.setCacheable(false);
return templateResolver;
}
}
Например, внутри моего файла свойств (messages_en.properties) у меня есть:
admin.greeting = Hello, Admin!
Вот так выглядит шаблон (файл HTML)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h3 th:text="#{admin.greeting}">Dear Admin,</h3>
<p th:text="#{admin.deposit.request.accepted(${amount}, ${user})}">The deposit request of AMOUNT euro made for user USER has been accepted.</p>
<p><strong th:text="#{email.generation}">This is an automated email.</strong></p>
<p th:text="#{email.regards}">Kind Regards,</p>
<p th:text="#{admin.regards}">Robots</p>
</body>
</html>
Ничего не помогло, и я не могу понять, почему. Использование переменных (обозначается $ {}) внутри шаблонов работает, но сообщения (с помощью # {}) не найдены.
Это класс, который я использую для вызова механизма шаблонов. Метод String returnTemplateHtmlContent(String templatePath, Locale locale, Map<String, Object> map) throws TemplateInputException, NullPointerException
- это метод, который выполняет фактическую обработку. Переданная локаль установлена на «en», карта содержит переменные для вставки в шаблоны (это работает).
public abstract class AbstractMailHelper {
SpringTemplateEngine springTemplateEngine;
protected static final String ENCODING = "UTF-8";
public AbstractMailHelper() {
}
public AbstractMailHelper(SpringTemplateEngine templateEngine) {
this.springTemplateEngine = templateEngine;
}
//Prepares values to be injected into template
protected Context prepareTemplateContext(Locale locale, Map<String, Object> contextMap) {
final Context context = new Context(locale);
context.setVariables(contextMap);
return context;
}
//returns as a string the template with the custom values inserted
protected String returnTemplateHtmlContent(String templatePath, Locale locale, Map<String, Object> map) throws TemplateInputException, NullPointerException {
return springTemplateEngine.process(templatePath, prepareTemplateContext(locale, map));
}
}