解析 WEB-INF 中的 Thymeleaf 模板

Resolve Thymeleaf templates in WEB-INF

我想使用 thymeleaf 来发送电子邮件来呈现电子邮件消息。这是我在 Spring 4 applicationContext.xml:

中的配置
<bean id="thymeleafMailEngine" class="org.thymeleaf.TemplateEngine">
    <property name="templateResolver" ref="thymeleafMailResolver" />
</bean>
<bean id="thymeleafMailResolver" class="org.thymeleaf.templateresolver.FileTemplateResolver">
    <property name="templateMode" value="XHTML" />
    <property name="prefix" value="src/main/webapp/WEB-INF/templates/" />
    <property name="characterEncoding" value="UTF-8" />
    <property name="cacheable" value="false"/>
</bean>
<bean id="websiteMailSender" class="com.mycompany.service.MailSenderWithAttachmentSupport">
    <property name="thymeleafEngine" ref="thymeleafMailEngine" />
    <property name="thymeleafResolver" ref="thymeleafMailResolver" />
</bean>

要发送我的电子邮件,我使用:

        MimeMessage msg=mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
            //...
            final Context ctx = new Context();
            ctx.setVariables(model); //model is a Map<String,Object>
            helper.setText(thymeleafEngine.process(template, ctx)); //line 89
        } catch(MessagingException me) {
            log.error("Cannot send email message");
        }

它生成此异常:

org.thymeleaf.exceptions.TemplateInputException: Error resolving template "my_template.html", template might not exist or might not be accessible by any of the configured Template Resolvers at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:246) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:924) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:898) at com.mycompany.service.MailSenderWithAttachmentSupport.send(MailSenderWithAttachmentSupport.java:89)

我刚刚找到了解决方案:

<bean id="thymeleafMailResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
    <property name="templateMode" value="XHTML" />
    <property name="prefix" value="/WEB-INF/templates/" />
    <property name="characterEncoding" value="UTF-8" />
    <property name="cacheable" value="false"/>
</bean>