Velocity模板的使用

Velocity模板是后端使用的非常频繁的一种技术。我们可以将信息动态加载到模板中,根据信息的不同,生成不同的内容,非常方便。
下面简单介绍一下使用

参数介绍:
templateName:模板名称
model:我们需要注入到模板中的参数,是一个map,例如{ "appName" :" 测试系统 " }
templateContent:模板的内容


 private String buildSendContent(String templateName,Map model,String templateContent) {
        // 替换模板初始化变量
        Properties prop = new Properties();
        //选择资源加载器,这里使用的是string加载器
        prop.put("resource.loader", "string");
        //资源加载器类名称
        prop.put("file.resource.loader.class", StringResourceLoader.class.getName());
        Velocity.init(prop);
	//存储模板内容的中央仓库
        StringResourceRepository repo = StringResourceLoader.getRepository();
        // 将模板内容存储进中央仓库
        if (StringUtils.isBlank(templateContent)) {
            repo.putStringResource(templateName, StringUtils.EMPTY);
        } else {
            repo.putStringResource(templateName, templateContent);
        }
        StringWriter writer = new StringWriter();
        VelocityContext context = new VelocityContext();
        //将需要生成的内容写进VelocityContext中,底层使用Map
        if(MapUtils.isNotEmpty(model)){
            Set<Map.Entry> set = model.entrySet();
            for (Map.Entry entry : set) {
                context.put(entry.getKey().toString(),entry.getValue());
            }
        }
        //将我们的内容写进模板中
        Velocity.mergeTemplate(templateName, "UTF-8", context, writer);
        //输出生成好的内容
        final String mailContent = writer.toString();
        return mailContent;

定义模板内容:
例如:
张三,你好,你正在充值${appName}的密码,时间为${createTime}

然后我们将appName的值和createTime的值注入即可。注意:这个名称要和我们注入的名称对应上,否则会注入失败。

对于模板的加载,Velocity一共定义了6种资源加载器,但是比较常用的有4种
我们使用的是String资源加载器,意为:模板是String类型注入到工程中。
另外有三种资源加载器,分别是:
(1).从项目文件中加载
(2).从类路径加载
(3).从jar包中加载
不再赘言,可以查看这篇文章。写的比较好。感谢这个作者的分享
https://www.cnblogs.com/ldbangel/p/6876661.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值