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

gur*_*rbi 3 java spring templates velocity jakarta-mail

最近我需要初始化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>
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

mail_template.vm中你想要使用类似的东西:

<li>Transfer start date: $date.format('medium_date', $backingObject.creationDate)</li>
Run Code Online (Sandbox Code Playgroud)

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

gur*_*rbi 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);
}
Run Code Online (Sandbox Code Playgroud)

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