How to configure Velocity Escape Tool with Spring Properties?

Ralph picture Ralph · Jan 2, 2012 · Viewed 9.2k times · Source

I create e-mails from templates via Velocity in a Spring Web Application. Now I need to HTML escape SOME of the values. I found the Velocity Escape Tool. But I did not get the configuration working.

What I have tryed so fare is (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>

Template (htmlEscapeTest.vm):

with escape: $esc.html($needEscape)

TestCase:

@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("&lt;test&gt;"));
}

But the Test failed, ...got: "with escape: $esc.html($needEscape)"

Can anybody give me a hint what I am doing wrong?


If I add new EscapeTool() explicite in the test:

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();

then it is working. But as far as I understand the documentation, the tools should be configured once in the properties file.

I am using Velocity Engine 1.7 and Velocity Tools 2.0.

Answer

Alig picture Alig · Nov 28, 2014

You can not configure the Tools directly in the VelocityEngine. What you do instead, is that when you use the VelocityEngineUtils that you pass any Tools within the model map:

ModelMap model = new ModelMap();
model.put("esc", new EscapeTool());
VelocityEngineUtils.mergeTemplateIntoString(
                velocityEngine, "template.vm", "UTF-8", model)

Or if you use the VelocityEngine directly you could do:

VelocityContext velocityContext = new VelocityContext(model);
velocityEngine.mergeTemplate(templateLocation, encoding, velocityContext, writer);