Velocity引擎无法找到资源

时间:2014-11-04 12:21:05

标签: java velocity

在我的应用程序中,用户可以接收电子邮件模板我正在使用velocity engine发送电子邮件。电子邮件模板位于WEB-INF/email_tempaltes/...目录中。

这是我的代码:

String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateLocation, "UTF-8", model);

其中templateLocationString variable,其中显而易见的是:

"/email_templates/request-feedback.vm"

以下是我发送邮件的方式:

private void sendEmail(final String toEmailAddresses, final String fromEmailAddress,
                           final String subject, final String attachmentPath,
                           final String attachmentName, final Mail mail, final String templateLocation) {
        Properties properties = new Properties();
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
                message.setTo(toEmailAddresses);
                message.setFrom(new InternetAddress(fromEmailAddress));
                message.setSubject(subject);
                Map<String, Object> model = new HashMap<String, Object>();
                model.put("phone", mail.getPhone());
                model.put("email", mail.getEmail());
                model.put("message", mail.getMessage());
                String body = VelocityEngineUtils.mergeTemplateIntoString(
                        velocityEngine, templateLocation, "UTF-8", model);
                message.setText(body, true);
                if (!StringUtils.isBlank(attachmentPath)) {
                    FileSystemResource file = new FileSystemResource(attachmentPath);
                    message.addAttachment(attachmentName, file);
                }
            }
        };
        this.mailSender.send(preparator);
    }

我在我的本地计算机上测试了电子邮件发送并且工作正常,但是当我在服务器上部署它时我得到了一个例外:

org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource /email_templates/request-feedback.vm'

我该如何解决?我应该在哪里存储电子邮件模板提前谢谢!

----------- EDITED:----------- 我已经创建了类目录ander WEB-INF并在那里添加了我的模板。

现在我得到这样的模板:

emailSender.sendEmail(mail.getEmail(), "info@somemail.com", "Your message was sent successfully", mail, "/classes/templates/request-sent-answer.vm");

并得到同样的错误:

Could not prepare mail; nested exception is org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 

1 个答案:

答案 0 :(得分:-1)

我不知道mergeTemplateIntoString的作用,但另一种解决方案是从类路径中检索模板并使用MessageFormat对其进行格式化。

String result;
final StringWriter templateData = new StringWriter();
final InputStream templateIn = YourClassName.class.getClassLoader().getResourceAsStream(path);
  for(int b=templateIn.read(); b != -1; b=templateIn.read()){
     templateData.write(b);
  }
templateIn.close();
result = MessageFormat.format(templateData.toString(), arguments);