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

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>

相关文章:

  • ubuntu 22.04 安装部署elasticsearch 7.10.0详细教程
  • DBSCAN(Density-Based Spatial Clustering of Applications with Noise)基于密度的聚类方法介绍
  • LeetCode 2389.和有限的最长子序列
  • Ubuntu 安装并使用 Elasticsearch
  • Go语言同步原语与数据竞争:数据竞争的检测工具
  • 【分析学】 实数
  • AI 产品设计头脑风暴
  • MySQL 数据库自动备份批处理工具介绍
  • B3865 [GESP202309 二级] 小杨的 X 字矩阵
  • Tomcat配置学习
  • 电阻篇---下拉电阻的取值
  • ASR-PRO语音识别可能出现的问题
  • Flutter 本地存储全面指南:从基础到高级实践
  • cocos2 使用 Layout 组件后,子节点 Label 高度变化后,抖动问题
  • AUTOSAR图解==>AUTOSAR_SRS_GPTDriver
  • C语言:Linux libc和glibc的历史
  • 1. NVIDIA驱动安装
  • SpringCloud框架全面学习指南
  • AC耦合与DC耦合
  • 本地访问远程vps中的sqlite数据库中的内容之(一)建立并访问ftp服务器
  • 动态网站制作流程/百度seo关键词优化工具
  • 网站规划问题/百度云登录入口
  • 有趣的网站有哪些推荐/教育培训机构有哪些
  • 郑州做网站公司排/打开网站搜索
  • ps网站首页设计/百度seo发帖推广
  • 天津做网站美工/seo超级外链工具免费