【发布时间】: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);
}
在 mail_template.vm 你想使用类似的东西:
<li>Transfer start date: $date.format('medium_date', $backingObject.creationDate)</li>
在解析模板时,如何确保 DateTool 正确初始化和使用?
【问题讨论】:
标签: java spring templates jakarta-mail velocity