Velocity如何直接从数据库读取模板内容,不需要vm文件

概要

在Java开发的过程中,增删改查的代码总是着浪费程序员的生命和热情。使用Velocity库来生成代码是一件非常轻松的事情,而绝大多数的项目都只是将代码模板存进静态文件中,进行读取和替换操作。想要最大限度的客制化,支持多种开发语言,我们必须抛弃vm文件!

目前探索出两种方式:

第一种方式:

自定义VM模板加载器

可以在这里读取数据库

import java.io.*;
import java.nio.charset.StandardCharsets;

import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.apache.velocity.util.ExtProperties;

/**
 * 自定义VM模板加载器
 *
 * @author xurenyi
 * @since 2023/12/22 16:45
 */
public class VmResourceLoader extends ResourceLoader {
    @Override
    public long getLastModified(Resource arg0) {
        return 0;
    }

    @Override
    public void init(ExtProperties configuration) {

    }

    /**
     * 动态加载vm文件内容
     *
     * @param source
     * @param encoding
     */
    @Override
    public Reader getResourceReader(String source, String encoding) throws ResourceNotFoundException {
        String str = "-- 菜单 SQL\n" +
                "insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
                "values('${functionName}', '${parentMenuId}', '1', '${businessName}', '${moduleName}/${businessName}/index', 1, 0, 'C', '0', '0', '${permissionPrefix}:list', '#', 'admin', sysdate(), '', null, '${functionName}菜单');\n" +
                "\n" +
                "-- 按钮父菜单ID\n" +
                "SELECT @parentId := LAST_INSERT_ID();\n" +
                "\n" +
                "-- 按钮 SQL\n" +
                "insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
                "values('${functionName}查询', @parentId, '1',  '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:query',        '#', 'admin', sysdate(), '', null, '');\n" +
                "\n" +
                "insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
                "values('${functionName}新增', @parentId, '2',  '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:add',          '#', 'admin', sysdate(), '', null, '');\n" +
                "\n" +
                "insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
                "values('${functionName}修改', @parentId, '3',  '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:edit',         '#', 'admin', sysdate(), '', null, '');\n" +
                "\n" +
                "insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
                "values('${functionName}删除', @parentId, '4',  '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:remove',       '#', 'admin', sysdate(), '', null, '');\n" +
                "\n" +
                "insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
                "values('${functionName}导出', @parentId, '5',  '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:export',       '#', 'admin', sysdate(), '', null, '');";
        InputStream inputStream = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
        Reader reader = new InputStreamReader(inputStream);
//        inputStream = new ByteArrayInputStream(reader.toString().getBytes(StandardCharsets.UTF_8));
        return reader;
    }

    @Override
    public boolean isSourceModified(Resource arg0) {
        return false;
    }
}

测试类

import java.io.StringWriter;
import java.util.Properties;

import com.ruoyi.common.constant.Constants;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class test {
    /**
     * 自定义VM资源加载器 测试
     */
    public static void main(String[] args) {
        // 创建引擎
        VelocityEngine ve = new VelocityEngine();
        Properties p = new Properties();
        // 设置自定义loader的名称srl
        p.put("resource.loader", "srl");
        // 指定读取的class文件,注意文件的包路径
        p.put("srl.resource.loader.class", "xxx.gen.tmpl.loader.VmResourceLoader");
        try {
            //进行初始化操作
            ve.init(p);
            //加载模板,设定模板编码
            Template t = ve.getTemplate("无所谓", Constants.UTF8);
            //设置初始化数据
            VelocityContext context = new VelocityContext();
            context.put("functionName", "系统管理");
            context.put("parentMenuId", "0");
            context.put("businessName", "system");
            context.put("moduleName", "sysUser");
            context.put("permissionPrefix", "system:sysUser");
            //设置输出
            StringWriter writer = new StringWriter();
            //将环境数据转化输出
            t.merge(context, writer);
            // 简化操作
//            ve.mergeTemplate("vm/sql/sql.vm", Constants.UTF8, context, writer);
            System.out.println(writer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 第二种方式:

 Velocity.evaluate

package com.redotsoft.gen.tmpl;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.StringWriter;

public class test2 {
    private static String str = "-- 菜单 SQL\n" +
            "insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
            "values('${functionName}', '${parentMenuId}', '1', '${businessName}', '${moduleName}/${businessName}/index', 1, 0, 'C', '0', '0', '${permissionPrefix}:list', '#', 'admin', sysdate(), '', null, '${functionName}菜单');\n" +
            "\n" +
            "-- 按钮父菜单ID\n" +
            "SELECT @parentId := LAST_INSERT_ID();\n" +
            "\n" +
            "-- 按钮 SQL\n" +
            "insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
            "values('${functionName}查询', @parentId, '1',  '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:query',        '#', 'admin', sysdate(), '', null, '');\n" +
            "\n" +
            "insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
            "values('${functionName}新增', @parentId, '2',  '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:add',          '#', 'admin', sysdate(), '', null, '');\n" +
            "\n" +
            "insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
            "values('${functionName}修改', @parentId, '3',  '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:edit',         '#', 'admin', sysdate(), '', null, '');\n" +
            "\n" +
            "insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
            "values('${functionName}删除', @parentId, '4',  '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:remove',       '#', 'admin', sysdate(), '', null, '');\n" +
            "\n" +
            "insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)\n" +
            "values('${functionName}导出', @parentId, '5',  '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:export',       '#', 'admin', sysdate(), '', null, '');";

    /**
     * 自定义VM资源加载器 测试
     */
    public static void main(String[] args) {
        // 创建引擎
        Velocity v = new Velocity();
        try {
            //进行初始化操作
            v.init();
            //设置初始化数据
            VelocityContext context = new VelocityContext();
            context.put("functionName", "系统管理");
            context.put("parentMenuId", "0");
            context.put("businessName", "system");
            context.put("moduleName", "sysUser");
            context.put("permissionPrefix", "system:sysUser");
            //设置输出
            StringWriter writer = new StringWriter();
            //将环境数据转化输出
            v.evaluate(context, writer, "无所谓", str);
            System.out.println(writer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
视频详细讲解,需要的小伙伴自行百度网盘下载,链接见附件,永久有效。 1. 课程概述 本课程从velocity engine也就是velocity引擎开始, 先讲解velocity的基本使用以及基础语法 , 然后再讲解velocity 的进阶内容velocity Tools , 以及velocity作为web项目的视图改如何使用 , 每一部分都会有一个综合案例将常用的语法和工具串联起来。 第一部分我们会使用velocity实现一个代码生成器 第二部分我们会使用velocity作为web项目的视图, 实现基础数据的CRUD 2. 课程特色 Velocity是Apache顶级项目从2007-02-08发布第一个可用版本开始, 一直广受欢迎 ! 但是遗憾的是 , 市面上并没有一款详细的Velocity教程 , 特别是最新版本的velocity使用, 相关资料更是少的可怜 ! 所以我们这套课程有如下特色 : l 从基础开始 : 只要有一些java开发的基础就可以学习第一部分velocity engine l 全面 : 本课程从基础的velocity engine 讲到进阶的velocity Tools , 从代码生成器到web开发 , 多种使用场景都有涉及 l 版本新 : 本课程讲解是基于最新的 velocity engine 2.2以及velocity Tools 3.0 3. 课程内容 第一部分 : velocity engine 基础 l velocity 简介 l 快速入门 l vtl 模板语法 l 代码生成器案例 第二部分 : velocity tools 高级进阶 l velocity tools 介绍 l GenericTools使用 l Velocity View 使用 l 自定义tools工具类 l springmvc整合velocity l 实现对用户数据的简单增删改查 4. 适用人群 本课程的定位是velocity的系统教学课程 , 从基础到进阶 , 所以只要对velocity感兴趣 , 想系统学习velocity的开发人员都可以学习本课程 ! 学习本课程对你有如下要求 : l 有一定的JAVA编程基础(velocity engine要求) l 有一定的web编程基础(velocity tools部分要求) l 了解SSM整合项目开发(综合案例要求)

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值