我有速度模板,一些将模板和POJO合并到文本中的方法。我检查了调试器,所有数据都在正确填充。我的问题是速度只能获得一个字段(queueName),但其余的不能。那是为什么?
模板:
<html>
<body>
<h3>Environment: ${environment}</h3>
<div>
#if ($monitoredQueues.size() > 0)
<table>
#foreach( $monitoredQueue in $monitoredQueues )
#set( $queueName = ${monitoredQueue.QueueName})
#set( $crMsgCount = ${monitoredQueue.CurrentMessagesCount})
#set( $prMsgCount = ${monitoredQueue.PreviousMessagesCount})
#set( $prCheckTime = ${monitoredQueue.PreviousCheckTime})
#set( $prEmailTime = ${monitoredQueue.PreviousEmailSentTime})
<tr>
<td>
<table>
<tr>
<td>
<p>Queue name: ${queueName}</p>
</td>
</tr>
<tr>
<td>
<p>Current messages count: ${crMsgCount}</p>
</td>
</tr>
<tr>
<td>
<p>Previous messages count: $!{prMsgCount}</p>
</td>
</tr>
<tr>
<td>
<p>Previous check time: $!{prCheckTime}</p>
</td>
</tr>
<tr>
<td>
<p>Previous email sent time: $!{prEmailTime}</p>
</td>
</tr>
</table>
</td>
</tr>
#end
</table>
#end
</div>
</body>
</html>
这是我的POJO
@Data //lombok annotation generates getters, setters, hash and equals
@Builder //lombok annotation generates builder
@NoArgsConstructor
@AllArgsConstructor
public class MonitoredQueue {
private Integer id;
private String queueName;
private Integer currentMessageCount;
private Integer previousMessageCount;
private LocalDateTime previousCheckDate;
private LocalDateTime previousEmailSentDate;
private String createdBy;
private LocalDateTime creationDate;
private String modifiedBy;
private LocalDateTime modificationDate;
}
合并方法
public String mergeTemplateIntoEmailText(List<MonitoredQueue> monitoredQueues, String environment) {
velocityEngine.init();
Template mailTemplate = velocityEngine.getTemplate(EMAIL_TEMPLATE);
VelocityContext velocityContext = new VelocityContext();
velocityContext.put(ENVIRONMENT, environment);
velocityContext.put(MONITORED_QUEUE, monitoredQueues);
StringWriter writer = new StringWriter();
mailTemplate.merge(velocityContext, writer);
return writer.toString();
}
这就是结果:
Environment: test
Queue name: XXXX Current messages count: $crMsgCount Previous messages count: $prMsgCount Previous check time: $prCheckTime Previous email sent time: $prEmailTime
我通过更改模板解决了我的问题。速度某种程度上在html树的深层某处松散了上下文。不知道为什么。
答案 0 :(得分:0)
确保您的POJO类为public
。如果您的POJO不公开:
@Data
@AllArgsConstructor
class Foo {
private String bar;
private String baz;
}
然后:
Foo foo = new Foo();
foo.setBar("lorem");
foo.setBaz("ipsum");
Template template = VELOCITY_ENGINE.getTemplate("/templates/sample.vm", UTF_8.name());
VelocityContext context = new VelocityContext(ImmutableMap.<String, Object>of("foo", foo));
StringWriter writer = new StringWriter();
template.merge(context, writer);
不会分别用${foo.bar}
和${foo.baz}
代替lorem
和ipsum
的值。
一旦我将Foo
设为public
类,速度就可以毫无问题地呈现其属性。
答案 1 :(得分:-1)
Velocity无法读取私有字段。你需要添加公共吸气剂。