【问题标题】:How to initialize Velocity DateTool within spring webapp?如何在 spring webapp 中初始化 Velocity DateTool?
【发布时间】:2014-07-03 08:40:22
【问题描述】:

最近我需要初始化 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);
}

ma​​il_template.vm 你想使用类似的东西:

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

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

【问题讨论】:

    标签: java spring templates jakarta-mail velocity


    【解决方案1】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 1970-01-01
      相关资源
      最近更新 更多