Ral*_*lph 12 java spring velocity
我在Spring Web Application中通过Velocity从模板创建电子邮件.现在我需要HTML转义一些值.我找到了Velocity 逃生工具.但我没有让配置工作.
我试过这样的票价是(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>
Run Code Online (Sandbox Code Playgroud)
模板(htmlEscapeTest.vm):
with escape: $esc.html($needEscape)
Run Code Online (Sandbox Code Playgroud)
测试用例:
@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>"));
}
Run Code Online (Sandbox Code Playgroud)
但测试失败了, ...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();
Run Code Online (Sandbox Code Playgroud)
然后它正在工作.但据我了解文档,应在属性文件中配置一次工具.
我正在使用Velocity Engine 1.7和Velocity Tools 2.0.
您无法直接在VelocityEngine中配置工具.你做的是,当你使用VelocityEngineUtils传递模型贴图中的任何工具时:
ModelMap model = new ModelMap();
model.put("esc", new EscapeTool());
VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, "template.vm", "UTF-8", model)
Run Code Online (Sandbox Code Playgroud)
或者,如果您直接使用VelocityEngine,您可以:
VelocityContext velocityContext = new VelocityContext(model);
velocityEngine.mergeTemplate(templateLocation, encoding, velocityContext, writer);
Run Code Online (Sandbox Code Playgroud)
警告:我是根据不久前有些模糊的记忆写的。里程可能会有所不同。
一些 Velocity 文档应该从“我如何在 a 中使用它VelocityView?”的角度来阅读。如果您想直接从 java 代码使用相同的功能,那么您需要更改一些细节。在这种情况下,我相信您没有Context正确创建。尝试遵循此处的独立示例,确保“要求 [ToolManager] 为您创建上下文”:
ToolManager manager = ...
Context context = manager.createContext();
Run Code Online (Sandbox Code Playgroud)
如果您使用的话,类似的事情可能会在幕后为您完成VelocityView。
| 归档时间: |
|
| 查看次数: |
8632 次 |
| 最近记录: |