java如何使用Spring属性配置Velocity Escape工具?
我在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
# 1 楼答案
改变这一点:
致:
# 2 楼答案
不能直接在VelocityEngine中配置工具。相反,当您使用VelocityEngineUtils时,您会传递模型地图中的任何工具:
或者,如果您直接使用VelocityEngine,您可以:
# 3 楼答案
警告:我是基于前一段时间的模糊记忆。里程可能会有所不同
一些Velocity文档应该从“如何在^{中使用它”的角度来阅读如果希望直接从java代码中使用相同的功能,那么需要更改一些细节。在这种情况下,我认为您没有正确地创建
Context
。试着遵循the standalone example here,确保你“要求[工具经理]为你创建一个上下文”:如果你使用
VelocityView
的话,类似的事情可能会在封面下为你做# 4 楼答案
这是我刚开始工作的一些代码。我发现标准工具是由ToolManager自动设置的
我的模板上有这个