
本文介绍如何在 Apache Velocity 1.7 中实现对 VelocityContext 中未被模板使用的变量进行检测,通过自定义 VelocityContext 子类跟踪键的写入与读取,从而在模板渲染后识别冗余变量并抛出异常。
本文介绍如何在 apache velocity 1.7 中实现对 `velocitycontext` 中未被模板使用的变量进行检测,通过自定义 `velocitycontext` 子类跟踪键的写入与读取,从而在模板渲染后识别冗余变量并抛出异常。
在使用 Apache Velocity 进行模板渲染时,一个常见但易被忽视的问题是:向 VelocityContext 中注入了多余变量(如示例中的 cardNumber),而模板(如 card.vm)并未引用它们。这虽不导致运行失败,却可能掩盖逻辑缺陷、增加维护成本,甚至引发安全或调试隐患。Velocity 默认不会校验上下文变量是否被实际使用,因此需借助扩展机制主动实现该能力。
核心思路是:重写 put() 和 get() 方法,分别记录“预期被使用”的键集合与“实际被访问”的键集合,渲染完成后比对二者差异。以下是一个生产可用的参考实现:
static class ReferenceCountingVelocityContext extends VelocityContext {
private final Set<string> keysToCheck = new HashSet();
private final Set<string> keysUsed = new HashSet();
@Override
public Object put(String key, Object value) {
if (key != null) {
keysToCheck.add(key);
}
return super.put(key, value);
}
@Override
public Object get(String key) {
if (key != null) {
keysUsed.add(key);
}
return super.get(key);
}
/**
* 检查是否存在写入但未被模板引用的变量
* @throws UnusedVelocityContextKeyException 当发现未使用变量时抛出
*/
public void checkForUnreferencedValues() throws UnusedVelocityContextKeyException {
Set<string> unusedKeys = new HashSet(keysToCheck);
unusedKeys.removeAll(keysUsed);
if (!unusedKeys.isEmpty()) {
throw new UnusedVelocityContextKeyException("Unused context keys: " + unusedKeys);
}
}
}
// 自定义异常类(建议定义)
static class UnusedVelocityContextKeyException extends RuntimeException {
public UnusedVelocityContextKeyException(String message) {
super(message);
}
}</string></string></string>
使用方式如下(适配原问题场景):
Apache Superset 是一个广泛采用的开源 BI 平台,用于 SQL 探索、图表构建和仪表板交付。当代理需要查询仓库数据、组装仪表板或使用成熟的分析界面解释指标而不是临时笔记本代码时,此技能非常有用。
ReferenceCountingVelocityContext context = new ReferenceCountingVelocityContext();
context.put("firstName", "tuk");
context.put("lastName", "man");
context.put("cardNumber", "1234"); // 此键未在 card.vm 中出现 → 将触发异常
Template t = velocityEngine.getTemplate("card.vm");
StringWriter writer = new StringWriter();
t.merge(context, writer);
// 渲染完成后立即校验
context.checkForUnreferencedValues(); // ← 此处抛出 UnusedVelocityContextKeyException
⚠️ 注意事项:
- 该方案依赖 get() 方法被 Velocity 引擎调用——仅当模板中存在 ${key} 表达式时才会触发;若变量仅用于 #if($key) 等指令,同样会被捕获。
- 若上下文被多个模板复用,或存在工具类(如 Spring 的 VelocityToolbox)自动注入辅助变量,请在 checkForUnreferencedValues() 前手动排除这些“合法冗余”键(例如通过白名单过滤)。
- VelocityContext 是非线程安全的,该子类也继承此特性;多线程环境下应确保每个模板渲染使用独立实例。
- 对于复杂嵌套对象(如 user.profile.name),本方案仅检测顶层键(user),不解析点号路径;如需深度校验,需结合 Uberspect 自定义反射访问器,但通常顶层键检查已覆盖绝大多数误用场景。
总结而言,通过轻量级继承与状态追踪,即可将 Velocity 的“静默忽略”行为转化为可验证、可告警的健壮流程。这一模式不仅适用于变量完整性校验,也可延伸用于模板覆盖率分析、上下文审计等工程化场景。










