如何在spring webapp中初始化Velocity DateTool?

时间:2014-07-03 08:40:23

标签: java spring templates javamail velocity

最近我需要初始化Velocity的DateTool,以便在生成的电子邮件中正确格式化日期。通常你用VelocityContext来做这件事,但是,因为我使用的是在xml中配置的spring的VelocityEngineFactoryBean,所以我得知 - 在使用VelocityEngineFactoryBean时如何初始化VelocityContext?

换句话说,我的设置:

webmvc-config.xml中

<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
  <property name="velocityProperties">
     <value>
        resource.loader=class
        class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
     </value>
  </property>

MailSender.java

public class CustomMailSender {

@Autowired
private VelocityEngine velocityEngine;

private void sendMail(final Object backingObject) {     
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);

            // Set subject, from, to, ....

            // Set model, which then will be used in velocity's mail template
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("backingObject", backingObject);
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail_template.vm", model);
            message.setText(text, true);

        }
    };
    this.javaMailSender.send(preparator);
}

mail_template.vm 中,您希望使用以下内容:

<li>Transfer start date: $date.format('medium_date', $backingObject.creationDate)</li>

如何确保在解析模板时正确初始化和使用DateTool?

1 个答案:

答案 0 :(得分:7)

经过几个小时的搜索后,结果非常简单:在初始化模型时再添加一行:

private void sendMail(final Object backingObject) {     
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);

            // Set subject, from, to, ....

            // Set model, which then will be used in velocity's mail template
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("backingObject", backingObject);

            // Add this line in order to initialize DateTool
            model.put("date", new DateTool());

            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail_template.vm", model);
            message.setText(text, true);

        }
    };
    this.javaMailSender.send(preparator);
}

之后,您可以在模板中使用 $ date