【发布时间】:2016-10-12 16:20:21
【问题描述】:
我在 Spring Web 应用程序中通过 Velocity 从模板创建电子邮件。现在我需要对一些值进行 HTML 转义。我找到了速度Escape Tool。但我没有让配置工作。
我尝试过的是(spring applicationContext.xml):
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="classpath:/velocity/emailTemplates" />
<property name="preferFileSystemAccess" value="false" />
<property name="overrideLogging" value="true" />
<property name="velocityProperties">
<util:properties>
<prop key="input.encoding">UTF-8</prop>
<prop key="output.encoding">UTF-8</prop>
<prop key="tools.toolbox">application</prop>
<prop key="tools.application.esc">org.apache.velocity.tools.generic.EscapeTool</prop>
</util:properties>
</property>
</bean>
模板(htmlEscapeTest.vm):
with escape: $esc.html($needEscape)
测试用例:
@Test
public void testHtmlEscapingSupport() {
final String needEscape = "<test>";
ModelMap model = new ModelMap();
model.addAttribute("needEscape", needEscape);
String result = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, HTML_ESCAPING_TEMPLATE_FILE, model);
assertThat(result, StringContains.containsString("<test>"));
}
但是测试失败了,...got: "with escape: $esc.html($needEscape)"
谁能告诉我我做错了什么?
如果我在测试中添加new EscapeTool()explicite:
VelocityContext velocityContext = new VelocityContext(model);
velocityContext.put("esc", new EscapeTool());
StringWriter writer = new StringWriter();
velocityEngine.mergeTemplate(HTML_ESCAPING_TEMPLATE_FILE, velocityContext, writer);
String result = writer.toString();
然后它正在工作。但据我了解文档,这些工具应该在属性文件中配置一次。
我正在使用 Velocity Engine 1.7 和 Velocity Tools 2.0。
【问题讨论】:
-
一般来说,我的经验是,当你想直接调用速度时,你必须手动设置上下文。您能否提供相关文档的链接?
-
您使用的是什么版本的 Velocity?您原来的 Escape Tools 链接指向 1.4,而这些链接指向 2.0。
-
@jtoberon:Velociti 引擎 1.7 和 Velociti 工具 2.0。 “你原来的逃生工具喜欢”是什么意思? (我相信上面评论中的两个链接都是针对 2.0 版的)
-
原始问题第三句中的链接:velocity.apache.org/tools/releases/1.4/generic/EscapeTool.html。抱歉,这不清楚。我隐约记得不久前遇到过类似的问题,所以我会将我记得的答案发布为以防万一。