Я использую тимелеаф весенний 5 на пружинном ботинке. Spring boot (2.0.2.RELEASE) и Thymeleaf-spring5 (3.0.11.RELEASE)
Ниже приведены мои конфигурации/изменения:
ПОМ
Код: Выделить всё
...
org.springframework.boot
spring-boot-starter-parent
2.0.2.RELEASE
...
org.springframework.boot
spring-boot-starter-thymeleaf
org.thymeleaf.extras
thymeleaf-extras-springsecurity4
org.thymeleaf
thymeleaf-spring5
3.0.11.RELEASE
...
Код: Выделить всё
@Configuration
public class NotificationTemplateConfiguration {
@Bean
@Qualifier(value = "myTemplateEngine")
public SpringTemplateEngine springTemplateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(myTemplateResolver());
return templateEngine;
}
@Bean
public SpringResourceTemplateResolver myTemplateResolver(){
SpringResourceTemplateResolver myTemplateResolver = new SpringResourceTemplateResolver();
myTemplateResolver.setPrefix("WEB-INF/templates/notifications/");
myTemplateResolver.setSuffix(".html");
myTemplateResolver.setTemplateMode(TemplateMode.HTML);
myTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
// I tried adding these lines but still it does not work
// myTemplateResolver.setOrder(0);
// myTemplateResolver.setCheckExistence(true);
return myTemplateResolver;
}
}
Код: Выделить всё
@Component
public class EmailService {
...
@Autowired
@Qualifier(value = "myTemplateEngine")
private SpringTemplateEngine m_myTemplateEngine;
...
private String buildContent() {
final Context context = new Context();
context.setVariable("recvName", getRecvName());
context.setVariable("inquiry", getInquiry());
context.setVariable("logoImageUrl", getLogoImageUrl());
// This is causing the error as it cannot find `WEB-INF/templates/notifications/inquiry-notification.html`, but this file really exists
return m_templateEngine.process("inquiry-notification", context);
}
public void sendEmail() throws MessagingException {
MimeMessage message = m_javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, ConstantUtil.CHARACTER_ENCODING);
String content = buildContent();
helper.setFrom(getFromEmail());
helper.setReplyTo(getNoReplyEmail());
helper.setText(content, true);
helper.setSubject(getSubject());
helper.setTo(getRecipientEmail());
m_javaMailSender.send(message);
}
}
Код: Выделить всё
Caused by: java.io.FileNotFoundException: class path resource [WEB-INF/templates/notifications/inquiry-notification.html] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:180)
at org.thymeleaf.spring5.templateresource.SpringResourceTemplateResource.reader(SpringResourceTemplateResource.java:103)
at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:223)
... 16 common frames omitted
Файл WEB-INF/templates/notifications/inquiry-notification.html существует и находится внутри WEB-INF/templates/notifications, даже если я проверяю файл войны. Проблема связана с m_templateEngine.process("inquiry-notification", context), поскольку он не может найти запрос-уведомление, даже если оно существует. Если я закомментирую это и просто верну жестко закодированную строку (только для тестирования)... электронное письмо будет отправлено без каких-либо ошибок.
Это WEB-INF/templates/notifications/inquiry -notification.html действительно существует, но я понятия не имею, почему он не может его найти.
Есть идеи, почему он не может найти файл внутри WEB-INF и как исправить это?
Обновление:
Если я изменю префикс на:
myTemplateResolver.setPrefix("classpath: /templates/notifications/");
и переместите папку из WEB-INF/templates/notifications/ в resources/templates/notifications.
Все работает, но я хочу использовать WEB-INF/templates/notifications/, а не ресурсы/шаблоны/уведомления.
Как прокомментировал @Ralph, это можно увидеть в исключении, что он читает из ресурса пути к классу, а не из контекстного ресурса.
Моя проблема сейчас в том, как я могу заставить его читать из контекста ресурс (WEB-INF/шаблоны/уведомления), а не из ресурса пути к классу (ресурсы/шаблоны/уведомления).
Подробнее здесь: https://stackoverflow.com/questions/688 ... de-web-inf
Мобильная версия