Velocity自带的转义对中文的支持不好,我们自己就写了转义的代码。
public class WebEscapeHtmlReference extends EscapeHtmlReference {
@Override
protected String escape(Object text) {
return escapeHtml(text);
}
private static String escapeHtml(Object value) {
if (value == null)
return null;
if (value instanceof String) {
String result = value.toString();
// "'<>&
result = result.replaceAll("&", "&").replaceAll(">", ">")
.replaceAll("<", "<").replaceAll("\"", """);
return result;
} else {
return value.toString();
}
}
}
Veloctiy配置
<!-- Velocity config --> <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"> <property name="resourceLoaderPath" value="/WEB-INF/views/" /> <property name="velocityPropertiesMap"> <props> <prop key="input.encoding">utf-8</prop> <prop key="output.encoding">utf-8</prop> <prop key="eventhandler.referenceinsertion.class">org.jamie.demo.springweb.framework.mvc.WebEscapeHtmlReference</prop> <prop key="eventhandler.escape.html.match">/^(?!\$\!?unesc_).*/</prop> <prop key="velocimacro.library">macros.vm</prop> </props> </property> </bean>对于某些不需要转义的输出(你必须肯定这个输出不包含用户的输入,或者用户的输入已经转义过),velocity变量以unesc_作为前缀。