二八佳人体似酥,腰间仗剑斩愚夫。虽然不见人头落,暗里教君骨髓枯。

上一章简单介绍了FreeMarker的使用,如果没有看过,请观看上一章

一. Velocity 的介绍

Velocity 的官方网址: https://velocity.apache.org/

与 FreeMarker 一样,也是模板引擎。

二. Java 使用Velocity

二.一 前期准备

创建一个 Maven 项目, 在 pom.xml 中添加 依赖

 <dependencies><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.3</version></dependency><!--测试junit--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><!--lombok依赖--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.16</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.6.1</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency></dependencies>

二.二 模板开发

这儿不与 Web 进行关联,不采用页面展示, 采用控制台输出。

二.二.一 基本信息展示

二.二.一.一 基本信息模板 vm

创建 basic.vm 文件

## Velocity Hello World
<html>
<body>## followed byHello,我是你们的老朋友,${name}## 放置读取的信息.#set($name="周小欢")#*如果同时设置的话,以 #set 为主。*#Hello,介绍一个新的朋友,${name}## 放置普通的对象信息${info.name} 的年龄是 ${info.age}
</body>
</html>

有基本的信息 name, 有对象的信息 info.name 和 info.age

可以通过 set 设置一个新的属性。

二.二.一.二 基本信息开发

    @Testpublic void basicFill() throws Exception{//1. 初始化模板引擎VelocityEngine ve=new VelocityEngine();//2. 设置相应的属性信息ve.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());//3. 进行初始化ve.init();//4.获取模板文件Template template=ve.getTemplate("basic.vm","utf-8");//5.设置变量VelocityContext root=new VelocityContext();root.put("name","岳泽霖");Map<String,Object> info=new HashMap<>();info.put("name","YJL");info.put("age",26);root.put("info",info);//6.进行合并,调用模板的 merge 方法, 将其进行填充。StringWriter stringWriter=new StringWriter();template.merge(root, stringWriter);System.out.println("输出信息值:"+stringWriter.toString());}

二.二.二 If 条件语句 展示

二.二.二.一 If 条件语句 vm

创建 if.vm 文件

## 放置if
##  可以使用条件表达式,进行处理。
#if(${age}>120)
年龄输入错误
#end
你的性别是:
#if(${sex}=='男')男性
#else女性
#end
你的成绩是:
#if(${score}>90)优
#elseif(${score}>80)良
#elseif(${score}>70)中
#elseif(${score}>60)及
#else差
#end

二.二.二.二 If 条件语句 开发

   @Testpublic void ifFillTest()throws Exception{//1. 创建模板引擎VelocityEngine velocityEngine=new VelocityEngine();//2. 设置属性velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");velocityEngine.setProperty("classpath.resource.loader.class",ClasspathResourceLoader.class.getName());//3. 进行初始化velocityEngine.init();//4.获取对应的模板信息Template template=velocityEngine.getTemplate("if.vm");//5. 构建 VelocityContext 对象,里面放置内容Map<String,Object> root=new HashMap<>();root.put("age",130);root.put("sex","男");root.put("score",86);VelocityContext velocityContext=new VelocityContext(root);//6. 找到StringWriter对象,进行合并StringWriter stringWriter=new StringWriter();template.merge(velocityContext,stringWriter);System.out.println("输出信息:"+stringWriter.toString());}

二.二.三 foreach 循环语句 展示

二.二.三.一 foreach 循环语句 vm

创建 foreach.vm 文件

#[[ 放置foreach 循环语句,进行处理 ]]#
## 放置 list或者数组 array
#foreach ($hobby in $hobbys)$hobby
#end
#if(${users})
<ul>#foreach($user in $users)<li>${user.name}</li>#end
</ul>
#end
## 放置map语句
#foreach($key in $infoMap.keySet())${key}------>${infoMap.get(${key})}
#end

二.二.三.二 foreach 循环语句 开发

User.java

@Data
public class User {private Integer id;private String name;private Integer sex;private Integer age;private String description;
}
   @Testpublic void foreachTest() throws Exception{//1.创建 VelocityEngine 引擎VelocityEngine velocityEngine=new VelocityEngine();//2. 设置属性velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");velocityEngine.setProperty("classpath.resource.loader.class",ClasspathResourceLoader.class.getName());//3. 进行初始化velocityEngine.init();//4.获取模板Template template=velocityEngine.getTemplate("foreach.vm");//5.进行填充数据Map<String,Object> root=new HashMap<>();String[] hobbys=new String[4];hobbys[0]="A";hobbys[1]="B";hobbys[2]="C";hobbys[3]="D";root.put("hobbys",hobbys);List<User> userList=getUserList();root.put("users",userList);Map<String,Object> infoMap=new HashMap<>();infoMap.put("name","YJL");infoMap.put("age",26);infoMap.put("sex","男");root.put("infoMap",infoMap);//6. 创建 VelocityContext 对象,填充数据。VelocityContext velocityContext=new VelocityContext(root);//7.StringWriter stringWriter=new StringWriter();//8. 通过 merge 方法,进行填充数据。template.merge(velocityContext,stringWriter);System.out.println("输出内容:"+stringWriter.toString());}private List<User> getUserList() {List<User> userList=new ArrayList<>();for(int i=1;i<=10;i++){User user=new User();user.setId(i);user.setName("蝴蝶"+i);user.setAge(i*3+1);user.setSex(i%2);user.setDescription("一个简单的描述");userList.add(user);}return userList;}

二.二.四 macro宏语句 展示

二.二.四.一 macro宏语句 vm

创建 macro.vm 文件

## 这是宏,可以理解成一个函数。
## 声明宏   sayHello 是方法名, $name 为参数
#macro(sayHello $name)我们要讲述: $name
#end## 使用宏
#sayHello("周小欢和岳泽霖的故事") ## 定义加法
#macro(add $num1,$num2)
#set($total=$num1+$num2)
## 直接使用相加的操作,还是字符串。$num1+$num2=${total}
#end
#add(2,3)

二.二.四.二 macro宏语句 开发

  @Testpublic void macroTests() throws Exception{//1. 初始化模板引擎VelocityEngine ve=new VelocityEngine();//2. 设置相应的属性信息ve.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());//3. 进行初始化ve.init();//4.获取模板文件Template template=ve.getTemplate("macro.vm","utf-8");//5.设置变量VelocityContext velocityContext=new VelocityContext();velocityContext.put("name","岳泽霖");//6.进行合并,调用模板的 merge 方法, 将其进行填充。StringWriter stringWriter=new StringWriter();template.merge(velocityContext, stringWriter);System.out.println("输出信息值:"+stringWriter.toString());}

二.二.五 include 包含文件

二.二.五.一 include 文件 vm

创建 foot.vm

<hr>
<i>Copyright (c) 2000 <a href="top.yueshushu.com">yueshushu_top</a>,<br>All Rights Reserved.
</i>

创建 footInclude.vm

<html>
<head><title>Include page</title>
</head>
<body>
<h1>Include page</h1>
<p>## -- 放置进去, #include 填充进去。 #include 填充进去。谢谢您来关注我: ${name}#include ("foot.vm")
</body>
</html>

二.二.五.二 include 开发

@Testpublic void includeFillTest()throws Exception{//1. 创建模板引擎VelocityEngine velocityEngine=new VelocityEngine();//2. 设置属性velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");velocityEngine.setProperty("classpath.resource.loader.class",ClasspathResourceLoader.class.getName());//3. 进行初始化velocityEngine.init();//4.获取对应的模板信息Template template=velocityEngine.getTemplate("footInclude.vm");//5. 构建 VelocityContext 对象,里面放置内容Map<String,Object> root=new HashMap<>();root.put("name","两个蝴蝶飞");VelocityContext velocityContext=new VelocityContext(root);//6. 找到StringWriter对象,进行合并StringWriter stringWriter=new StringWriter();template.merge(velocityContext,stringWriter);System.out.println("输出信息:"+stringWriter.toString());}

三. 使用 Velocity 配置模板文件

可以使用 Velocity 的配置文件, 通过往模板里面填充属性,来创建特定的文件。

如生成一个基本的 Main 类

三.一 模板 vm

package ${packageName};
/**
@author: ${author}
@Date: ${createDate}
@Description: ${classDescription}
*/
public class ${className}{
/**
功能描述: ${mainMethodDesc}
*/
public static void main(String []args){System.out.println("${info}");}
}

三.二 模板类创建

public class MainTests {@Testpublic void mainTests() throws Exception{//1. 初始化模板引擎VelocityEngine ve=new VelocityEngine();//2. 设置相应的属性信息ve.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());//3. 进行初始化ve.init();//4.获取模板文件Template template=ve.getTemplate("main.vm","utf-8");//5.设置变量Map<String,Object> root=getMainMap();VelocityContext velocityContext=new VelocityContext(root);//6.进行处理,发送到模板文件里面。PrintWriter printWriter=new PrintWriter("src\\main\\java\\com\\zk\\velocity\\VelocityMain.java");template.merge(velocityContext,printWriter);//刷新并关闭printWriter.flush();printWriter.close();System.out.println("生成文件成功");}private Map<String,Object> getMainMap() {Map<String,Object> root=new HashMap<>();root.put("packageName","com.zk.velocity");root.put("author","zk");root.put("createDate",new Date());root.put("classDescription","一个测试Velocity 自动生成类");root.put("className","VelocityMain");root.put("mainMethodDesc","一个普通的测试方法");root.put("info","Velocity 创建类生成信息");return root;}
}

生成的模板文件类:

本章节的代码放置在 github 上:

https://github.com/yuejianli/springboot/tree/develop/Velocity

谢谢您的观看,如果喜欢,请关注我,再次感谢 !!!

Velocity的使用相关推荐

  1. 卡尔曼滤波— Constant Velocity Model

    假设你开车进入隧道,GPS信号丢失,现在我们要确定汽车在隧道内的位置.汽车的绝对速度可以通过车轮转速计算得到,汽车朝向可以通过yaw rate sensor(A yaw-rate sensor is ...

  2. aa bb ccc java,TinyTemplate(Velocity Plus版)即将火热推出~~~

    原本是没有本身写一个模板引擎的计划的,由于按个人理解,一直认识这种"语言"级的引擎,难度是很是大的.总感受本身的水平不够,所以不敢有这个念头.直到大量使用Velocty的时候,碰到 ...

  3. Velocity 入门(一)

    Velocity是一种Java模版引擎技术,该项目由Apache提出.因为非常好用,和工作中有啥用,所以我在在理简单的入门一下. 网上找了很多教程,写的不是很明白,要么就是全部拷贝下来时候运行不起来. ...

  4. spring mvc velocity 配置备忘

    2019独角兽企业重金招聘Python工程师标准>>> Spring里面最重要的概念是IOC和AOP,还有两项很重要的模块是事务和MVC,对于IOC和AOP,我们要深究其源码实现,对 ...

  5. Velocity判断空的方法

    Velocity中没有null,那么怎么判断null呢 1.在velocity中,非null被认为是真的,所以,可以如下用: #if($!变量名)// 变量不为空的代码 #else// 变量为空的代码 ...

  6. Velocity文档(3)

    2019独角兽企业重金招聘Python工程师标准>>>     velocity.properties 的一些配置项 velocimcro.library属性:指定自己的模板库,多个 ...

  7. velocity自定义标签和指令

    velocity本身支持自定义标签和指令的扩展, 在 Velocity 模板语言的语法中,以美元符 $ 开头的为变量的声明或者引用,而以井号 # 开头的语句则为 Velocity 的指令(Direct ...

  8. java中velocity定义宏标签_velocity自定义标签和指令(转:zwj)

    velocity本身支持自定义标签和指令的扩展,我们看看扩展指令的步骤及searchweb2的应用场景, 1.使用方法 在 Velocity 模板语言的语法中,以美元符 $ 开头的为变量的声明或者引用 ...

  9. Velocity笔记--使用Velocity获取动态Web项目名的问题

    以前使用jsp开发的时候,可以通过request很轻松的获取到根项目名,现在换到使用velocity渲染视图,因为已经不依赖servlet,request等一些类的环境,而Web项目的根项目名又不是写 ...

  10. freemarker中运算符_如何在Web应用系统表示层开发中应用Velocity模板技术

    软件项目实训及课程设计指导--如何在Web应用系统表示层开发实现中应用Velocity模板技术 1.分离Web表示层的数据处理和展现逻辑的常见的应用技术 分离Web表示层的数据处理和展现逻辑是目前企业 ...

最新文章

  1. vs2012中使用localdb实例还原一个sql server 2008r2版本的数据库
  2. 算法提高课-图论-单源最短路的综合应用-AcWing 342. 道路与航线:最短路dijkstra、拓扑排序 、综合题、好题
  3. CoordinatorLayout+AppBarLayout实现上滑隐藏ToolBar-Android M新控件
  4. php中插入表格 标签,PHP_HTML中的表格元素,一,table标签。tablegt - phpStudy
  5. final/override控制
  6. uniny 物体运动到一个点停止_人教版高中英语必修五Unit 5 单词详解
  7. 字体单独设置样式_Glyphs 官方教程 | 字体命名
  8. Linux下python安装升级详细步骤 | Python2 升级 Python3
  9. html5调用系统声音1s响一次_20款奔驰GLC260提车改柏林之声音响,音乐诉请,为爱发声!...
  10. readline_Swift readLine(),Swift print()
  11. python实现多进程监听声音播放并绘图
  12. 开源音乐下载神器XMusicDownloader更新,支持歌单一键下载,支持无损音乐
  13. web安全:通俗易懂,以实例讲述破解网站的原理及如何进行防护!如何让网站变得更安全。
  14. 水溶性CdSe/ZnS量子点(表面由亲水配体包裹的核/壳型荧光纳米材料)
  15. jmeter-same user on each interation
  16. 三部门禁止对新能源车限购 专家:京沪情况复杂,政策仍不明朗
  17. 如何选择企业电脑加密软件,知道这几点一定不后悔!
  18. 测试固态参数的软件,BT测试告诉你 SSD 那些性能参数最重要
  19. 搜狗输入法如何输入直角引号(「『』」 )
  20. BZOJ3681: Arietta

热门文章

  1. canvas抖音八卦时钟,轻喷
  2. Ubuntu环境下制作win7-U盘引导盘
  3. 秀米图文编辑对接UEditor富文本编辑器样式丢失
  4. android微信配色,万能微信公众号配色模板(神仙配色太好看了)
  5. Ubuntu18.04 谷歌浏览器安装商店助手
  6. ELk日志分析系统搭建
  7. P.W.N. CTF - MISC - Canadian FOI
  8. 思考的力量—谈谈程序员成长背后的思考力
  9. 华为手机html乱码,华为手机系统语言变成乱码了怎么办?
  10. Java的发展 Java在不同系统下的开发环境 Java语言特性 Java实现跨平台