当前位置: 首页 > ops >正文

Velocity提取模板变量

目录

  • 前言
  • 实现代码

前言

  • 提取变量用正则也能做,但我看另一个项目用freemarker提取了模板的变量,就想着Velocity是不是也能做,搜了一圈没搜到,于是去debug了Velocity源码,发现变量最终会存在Node数组里。
    在这里插入图片描述

实现代码

  • 我只要能获取到Node [] children数组对象的数据就可以了。
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.engine.velocity.VelocityEngine;
import cn.hutool.extra.template.engine.velocity.VelocityTemplate;
import com.zbkj.common.constants.Constants;
import org.apache.velocity.runtime.parser.node.ASTIdentifier;
import org.apache.velocity.runtime.parser.node.ASTReference;
import org.apache.velocity.runtime.parser.node.ASTprocess;
import org.apache.velocity.runtime.parser.node.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;/*** @author zzq* @description Velocity工具类* @date 6/12/2025 14:12:44*/
public class VelocityUtil {private static final Logger log = LoggerFactory.getLogger(VelocityUtil.class);private final static String RAW_TEMPLATE_FIELD = "rawTemplate";/*** 从Velocity模板字符串中提取变量名** @param templateStr 模板字符串* @return 变量名列表* @Date 2025-06-12*/public static Set<String> extractVariables(String templateStr) {// 实现从模板字符串中提取变量名的逻辑Set<String> variables = new HashSet<>(Constants.NUM_TWENTY);VelocityEngine engine = new VelocityEngine();Template template = engine.getTemplate(templateStr);Field rawTemplateField = ReflectionUtils.findField(VelocityTemplate.class, RAW_TEMPLATE_FIELD);ReflectionUtils.makeAccessible(rawTemplateField);org.apache.velocity.Template rawTemplate = (org.apache.velocity.Template) ReflectionUtils.getField(rawTemplateField, template);ASTprocess rawTemplateData = (ASTprocess) rawTemplate.getData();if (!ObjectUtils.isEmpty(rawTemplateData)) {int nodeLength = rawTemplateData.jjtGetNumChildren();for (int i = 0; i < nodeLength; i++) {StringBuilder sb = new StringBuilder();// 第一级节点Node child = rawTemplateData.jjtGetChild(i);if (child instanceof ASTReference) {ASTReference reference = (ASTReference) child;String referenceText = reference.getRootString();sb.append(referenceText);
//                    log.info("Reference: " + referenceText);int nodeGrandLen = reference.jjtGetNumChildren();// 子孙节点for (int j = 0; j < nodeGrandLen; j++) {Node grandChild = reference.jjtGetChild(j);if (grandChild instanceof ASTIdentifier) {ASTIdentifier identifier = (ASTIdentifier) grandChild;sb.append(StrUtil.DOT + identifier.getIdentifier());
//                            log.info("Identifier: " + identifier.getIdentifier());}}variables.add(sb.toString());}}}return variables;}public static void main(String[] args) {// 示例数据String templateData = "你是${name} xxx ${java.lang.String.XTEST} ${java.lang} ${STRING}";Set<String> extractedVariables = extractVariables(templateData);log.info("Extracted Variables: " + extractedVariables);}
}
  • 运行效果
    在这里插入图片描述

  • 本身项目是Spring Boot,其他程序依赖

<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>4.5.7</version>
</dependency><!-- velocity代码生成使用模板 -->
<dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.3</version>
</dependency>
http://www.xdnf.cn/news/14396.html

相关文章:

  • 项目三 - 任务7:开发名片管理系统
  • SCAU大数据技术原理期末复习|第10、11章
  • ansible模块使用实践
  • UnityDots学习(六)
  • 手动 + 自动双方案组合:Innocise 壁虎吸盘灵活适配多场景无损搬运需求
  • 谷歌浏览器编译windows版本
  • Vue3相关知识1
  • STM32 HAL库学习 RNG篇
  • 编译链接实战(32)动态库的本质和原理
  • 循环神经网络及其变体
  • 数据库核心技术深度剖析:事务、索引、锁与SQL优化实战指南(第六节)-----InnoDB引擎
  • 软件设计模式入门
  • 力扣Hot100每日N题(17~18)
  • Vue学习001-创建 Vue 应用
  • anaconda安装教程
  • 板凳-------Mysql cookbook学习 (十--7)
  • 使用pinia代替vuex处理登录流程
  • 什么是扩展运算符?有什么使用场景?
  • 强化学习怎么入门?
  • Vue3 跨多个组件方法调用:简洁实用的解决方案
  • 人工智能基础知识笔记十:降维技术
  • cache的学习
  • 扣子开发平台 Agent 开发教程(一)
  • Adoquery 转AdoDataSet
  • LeetCode 1385.两个数组间的距离值
  • Kafka 可靠性保障:消息确认与事务机制(一)
  • vue3 +spring boot文件上传
  • 【Go语言-Day 1】扬帆起航:从零到一,精通 Go 语言环境搭建与首个程序
  • 操作系统核心名词解释--期末简答题快速复习
  • cuda编程笔记(2.5)--简易的应用代码