如何使用弹簧属性配置速度逃逸工具?

2022-09-04 03:47:03

我通过 Spring Web 应用程序中的 Velocity 从模板创建电子邮件。现在我需要HTML转义一些值。我找到了速度逃逸工具。但是我没有让配置工作。

我尝试过的是(弹簧应用程序context.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)

测试用例:

@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;"));
}

但测试失败了,...got: "with escape: $esc.html($needEscape)"

任何人都可以给我一个提示,我做错了什么吗?


如果我在测试中添加显式:new EscapeTool()

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

您不能直接在 VelocityEngine 中配置工具。相反,当您使用 VelocityEngineUtils 时,您会在模型映射中传递任何工具:

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

或者,如果您直接使用VelocityEngine,则可以执行以下操作:

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

答案 2

警告:我是基于前一段时间有些模糊的记忆。里程可能会有所不同。

一些 Velocity 文档应该从“我如何在一个中使用这个”如果你想直接从java代码中使用相同的功能,那么你需要改变一些细节。在这种情况下,我相信你没有正确地创建。尝试遵循此处的独立示例,确保“要求 [工具管理器] 为您创建上下文”:VelocityViewContext

ToolManager manager = ...
Context context = manager.createContext();

如果您使用,可能会在盖子下为您完成类似的事情。VelocityView


推荐