在WEB-INF中解析Thymeleaf模板

时间:2015-05-27 07:00:03

标签: java spring spring-mvc thymeleaf

我想使用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:解析错误   模板&#34; my_template.html&#34;,模板可能不存在或可能不存在   任何配置的模板解析器都可以访问   org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:246)     在org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104)at 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)

1 个答案:

答案 0 :(得分:0)

我刚刚找到了解决方案:

<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>