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