Velocity模板引擎

velocity简介

  1. velocity介绍
    Velocity是一个基于Java的模板引擎,可以通过特定的语法获取在java对象的数据,填充到模板中,从而实现界面和java代码的分离
    image.png

  2. 应用场景

  • Web应用程序:作为为应用程序的视图,展示数据。
  • 源代码生成 :velocity可用于基于模板生成Java源代码
  • 自动电子邮件:网站注册,认证等的电子邮件模板
  • 网页静态化:基于velocity模板,生成静态网页
  1. velocity结构
    image.png

Velocity主要分为app、context、runtime和一些辅助util几个部分。

  • app模块:主要封装了一些接口,暴露给使用者使用。主要有两个类,分别是Velocity(单例)和VelocityEngine。
  • Context模块:主要封装了模板渲染需要的变量
  • Velocity主要分为app、context、runtime和一些辅助util几个部分。
  • Runtime模块:整个Velocity的核心模块,Runtime模块会将加载的模板解析成语法树,Velocity调用mergeTemplate方法时会渲染整棵树,并输出最终的渲染结果。
  • RuntimeInstance类为整个velocity渲染提供了一个单例模式,拿到了这个实例就可以完成渲染过程了。

快速入门

1.需求分析

使用velocity定义html模板,将动态数据填充到模板中,形成一个html

2. 实现步骤

  1. 创建maven项目
    image.png

  2. 引入依赖

	<dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>
 <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
  1. 新建目录vms,然后新建html模板后缀名重名为vm
    image.png
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>velocity_01</title>
</head>
<body>
hello,${name}
</body>
</html>
  1. 编写测试类生成模板文件

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

/**
 * @Author Joker DJ
 * @Date 2021/7/17 20:32
 * @Version 1.0
 */

public class velocity01 {
    @Test
    public void test01() throws IOException {
        //1.设置velocity的资源加载类
        Properties prop = new Properties();
        prop.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //2.加载velocity引擎
        Velocity.init(prop);
        //3.加载velocity容器
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("name","velocity");
        //4.加载velocity模板
        Template template = Velocity.getTemplate("vms/01-quikstart.vm", "utf-8");
        //5.合并数据
        FileWriter fileWriter = new FileWriter("D:\\soft\\software\\work\\学习练习\\velocity\\velocity_01\\src\\main\\resources\\html\\01-quikstart.html");
        template.merge(velocityContext,fileWriter);
        //6.释放资源
        fileWriter.close();
    }
}

image.png

基础语法

VTL介绍

Velocity Template Language(VTL),是Velocity中提供的一种模版语言,旨在提供最简单和最干净的方法来将动态内容合并到网页中。简单来说VTL可以将程序中的动态数展示到网页中

VTL的语句分为4大类:注释非解析内容引用和指令

VTL注释

语法
  1. 行注释
## 行注释内容
  1. 块注释
#*
块注释内容1
块注释内容2
*#
  1. 文档注释
#**
文档注释内容1
文档注释内容2
**#
示例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>velocity_01</title>
</head>
<body>
## 行注释内容

#*
块注释内容1
块注释内容2
*#

#**
文档注释内容1
文档注释内容2
**#
</body>
</html>

非解析内容

所谓非解析内容也就是不会被引擎解析的内容。

语法
#[[
非解析内容1
非解析内容2
]]#
示例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>velocity_01</title>
</head>
<body>
#[[
非解析内容1
非解析内容2
]]#
</body>
</html>

引用

变量引用
语法

引用语句就是对引擎上下文对象中的属性进行操作。语法方面分为常规语法( 属 性 ) 和 正 规 语 法 ( 属性)和正规语法( )({属性})。

$变量名,若上下文中没有对应的变量,则输出字符串"$变量名"
${变量名},若上下文中没有对应的变量,则输出字符串""${变量名}"

$!变量名,若上下文中没有对应的变量,则输出空字符串""
$!{变量名},若上下文中没有对应的变量,则输出空字符串""
示例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>变量引用</title>
</head>
<body>
常规语法:$name
正规语法:${name}
##$变量名,若上下文中没有对应的变量,则输出字符串"$变量名"
##${变量名},若上下文中没有对应的变量,则输出字符串""${变量名}"
##$!变量名,若上下文中没有对应的变量,则输出空字符串""
##$!{变量名},若上下文中没有对应的变量,则输出空字符串""
常规语法:$!name
正规语法:$!{name}
</body>
</html>
package com.JokerDJ.VelocityTest;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

/**
 * @Author Joker DJ
 * @Date 2021/7/17 20:32
 * @Version 1.0
 */

public class velocity02 {
    @Test
    public void test01() throws IOException {
        //1.设置velocity的资源加载类
        Properties prop = new Properties();
        prop.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //2.加载velocity引擎
        Velocity.init(prop);
        //3.加载velocity容器
        VelocityContext velocityContext = new VelocityContext();
//        velocityContext.put("name","velocity");
        //4.加载velocity模板
        Template template = Velocity.getTemplate("vms/02-cite-变量引用.vm", "utf-8");
        //5.合并数据
        FileWriter fileWriter = new FileWriter("D:\\soft\\software\\work\\学习练习\\velocity\\velocity_01\\src\\main\\resources\\html\\02-cite-变量引用.html");
        template.merge(velocityContext,fileWriter);
        //6.释放资源
        fileWriter.close();
    }
}

输出内容
image.png

属性引用

语法
$变量名.属性,若上下文中米有对应的变量,则输出字符串"$变量名.属性"
${变量名.属性}若上下文中没有对应的变量,则输出字符串"${变量名.属性}"
$!变量名.病性若上下文中没有对应的变量,则输出字符串""
$!{变量名.属性}若上下文中没有对应的变量,则输出字符串""
示例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>变量引用</title>
</head>
<body>
常规语法:$user.username
正规语法:${user.username}

常规语法:$!user.username
正规语法:$!{user.username}
</body>
</html>
package com.JokerDJ.VelocityTest;

import com.JokerDJ.VelocityTest.Pojo.user;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

/**
 * @Author Joker DJ
 * @Date 2021/7/17 20:32
 * @Version 1.0
 */

public class velocity03 {
    @Test
    public void test01() throws IOException {
        //1.设置velocity的资源加载类
        Properties prop = new Properties();
        prop.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //2.加载velocity引擎
        Velocity.init(prop);
        //3.加载velocity容器
        user user = new user();
        user.setUsername("张三");
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("user",user);
        //4.加载velocity模板
        Template template = Velocity.getTemplate("vms/03-cite-属性引用.vm", "utf-8");
        //5.合并数据
        FileWriter fileWriter = new FileWriter("D:\\soft\\software\\work\\学习练习\\velocity\\velocity_01\\src\\main\\resources\\html\\03-cite-属性引用.html");
        template.merge(velocityContext,fileWriter);
        //6.释放资源
        fileWriter.close();
    }
}

image.png

方法引用

方法引用实际就是指方法调用操作,关注点返回值和参数,方法的返回值将输出到最终结果中

语法
$变量名.方法([入参1[,入参2]*]?),常规写法
${变量名.方法([入参1[,入参2]*]?)},正规写法
$!变量名.方法([入参1[,入参2]*?),常规写法
$!{变量名.方法([入参1[,入参2]*]?)},正规写法
示例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>方法引用</title>
</head>
<body>
常规语法:$str.split(",")-------$now.getTime()
正规语法:${str.split(",")}-------${now.getTime()}

常规语法:$!str.split(",")-------$!now.getTime()
正规语法:$!{str.split(",")}-------$!{now.getTime()}
</body>
</html>
package com.JokerDJ.VelocityTest;

import com.JokerDJ.VelocityTest.Pojo.user;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

/**
 * @Author Joker DJ
 * @Date 2021/7/17 20:32
 * @Version 1.0
 */

public class velocity04 {
    @Test
    public void test01() throws IOException {
        //1.设置velocity的资源加载类
        Properties prop = new Properties();
        prop.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //2.加载velocity引擎
        Velocity.init(prop);
        //3.加载velocity容器
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("str","hello,Velocity");
        velocityContext.put("now",new Date());
        //4.加载velocity模板
        Template template = Velocity.getTemplate("vms/04-cite-方法引用.vm", "utf-8");
        //5.合并数据
        FileWriter fileWriter = new FileWriter("D:\\soft\\software\\work\\学习练习\\velocity\\velocity_01\\src\\main\\resources\\html\\04-cite-方法引用.html");
        template.merge(velocityContext,fileWriter);
        //6.释放资源
        fileWriter.close();
    }
}
	

指令

set

作用:在页面定义变量
语法:#set($变量=值)
示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>方法引用</title>
</head>
<body>
#set($str="hello word")
#set($int=10)
#set($arr=[1,2,3])
#set($boolean=true)
#set($maps={"key1":"value1","key2":"value2"})

## 再声明变量的时候 也可以引用变量
#set($name="JokerDJ")
#set($map={"key1":$!{name},"key2":"value2"})
## 引用变量 获取
字符串:$!{str}
数值型:$!{int}
布尔型:$!{boolean}
数组型:$!{arr}
map.key1:$!{map.key1}
map.key2:$!{map.key2}
</body>
</html>
package com.JokerDJ.VelocityTest;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

/**
 * @Author Joker DJ
 * @Date 2021/7/17 20:32
 * @Version 1.0
 */

public class velocity05 {
    @Test
    public void test01() throws IOException {
        //1.设置velocity的资源加载类
        Properties prop = new Properties();
        prop.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //2.加载velocity引擎
        Velocity.init(prop);
        //3.加载velocity容器
        VelocityContext velocityContext = new VelocityContext();
        //4.加载velocity模板
        Template template = Velocity.getTemplate("vms/05-set指令.vm", "utf-8");
        //5.合并数据
        FileWriter fileWriter = new FileWriter("D:\\soft\\software\\work\\学习练习\\velocity\\velocity_01\\src\\main\\resources\\html\\05-set指令.html");
        template.merge(velocityContext,fileWriter);
        //6.释放资源
        fileWriter.close();
    }
}

image.png

if/elseif/else

作用:进行逻辑判断
语法

#if(判断条件)
....
#elseif(判断条件)
....
#else
....
#end

示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>方法引用</title>
</head>
<body>
#set($lag="Java")
#if($lag.equals("Java"))
java开发工程师
#elseif($lag.equals("PHP"))
PHP开发工程师
#else
开发工程师
#end
</body>
</html>	
package com.JokerDJ.VelocityTest;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

/**
 * @Author Joker DJ
 * @Date 2021/7/17 20:32
 * @Version 1.0
 */

public class velocity06 {
    @Test
    public void test01() throws IOException {
        //1.设置velocity的资源加载类
        Properties prop = new Properties();
        prop.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //2.加载velocity引擎
        Velocity.init(prop);
        //3.加载velocity容器
        VelocityContext velocityContext = new VelocityContext();
        //4.加载velocity模板
        Template template = Velocity.getTemplate("vms/06-if指令.vm", "utf-8");
        //5.合并数据
        FileWriter fileWriter = new FileWriter("D:\\soft\\software\\work\\学习练习\\velocity\\velocity_01\\src\\main\\resources\\html\\06-if指令.html");
        template.merge(velocityContext,fileWriter);
        //6.释放资源
        fileWriter.close();
    }
}

foreach

作用:遍历循环数组或集合
语法

#foreach($item in $items)
	...
	[#break]
#end
  • $items:需要变量的对象或集合
  • $item:变量名称,变量的每一项
  • [#break]:退出循环
  • 内置属性
    1. f o r e a c h . i n d e x : 获 取 便 利 的 索 引 , 从 0 开 始 2. foreach.index:获取便利的索引,从0开始 2. foreach.index便02.foreach.count:获取遍历的次数,从1开始

示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
#foreach($item in $strs)
$item
#end

#foreach($item in $users)
    $item.username
#end
</body>
</html>
package com.JokerDJ.VelocityTest;

import com.JokerDJ.VelocityTest.Pojo.user;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @Author Joker DJ
 * @Date 2021/7/17 20:32
 * @Version 1.0
 */

public class velocity07 {
    @Test
    public void test01() throws IOException {
        //1.设置velocity的资源加载类
        Properties prop = new Properties();
        prop.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //2.加载velocity引擎
        Velocity.init(prop);
        //3.加载velocity容器
        VelocityContext velocityContext = new VelocityContext();
        String[] strs = {"苹果", "三星", "小米", "华为"};
        List<user> users = new ArrayList<>();
        users.add(new user("小明"));
        users.add(new user("小蓝"));
        users.add(new user("小红"));

        velocityContext.put("strs",strs);
        velocityContext.put("users",users);
        //4.加载velocity模板
        Template template = Velocity.getTemplate("vms/07-foreach指令.vm", "utf-8");
        //5.合并数据
        FileWriter fileWriter = new FileWriter("D:\\soft\\software\\work\\学习练习\\velocity\\velocity_01\\src\\main\\resources\\html\\07-foreach指令.html");
        template.merge(velocityContext,fileWriter);
        //6.释放资源
        fileWriter.close();
    }
}

image.png

引入资源

include

作用:引入外部资源,引入的资源不会被引擎所解析
语法:#include(resource)
resource可以为单引号或双引号的字符串,也可以为**$变量**,内容为外部资源路径。注意:路径如果为相对路径,则以引擎配置的文件加载器加载路径作为参考

示例

<! DOCTYPE html>
<html 1ang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title></head>
<body>
#include("demo8 . vm")
</body>
</html>

parse

作用:引入外部资源,引入的资源将被引擎所解析
语法:#parse(resource)
resource可以为单引号或双引号的字符串,也可以为**$变量**,内容为外部资源路径。注意:路径如果为相对路径,则以引擎配置的文件加载器加载路径作为参考
示例

<! DOCTYPE html>
<html 1ang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title></head>
<body>
#parse("demo8 . vm")
</body>
</html>

define

作用:定义重用模块(不带参数)
语法:

#define($模块名称)
模块内容
#end

示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
#define($table)
    <table>
        ...
    </table>
#end

## 引用定义好的模块
    $table
</body>
</html>

evaluate

作用:动态计算,动态计算可以让我们在字符串中使用变量
语法:#evalute(“计算语句”)

< ! DOCTYPE htm1>
<html 1ang="en ">
<head>
    <meta charset="UTF-8">
    <title>Title</title></head>
body>
<h1>动态计算</h1>
#set($name = "over")
#evaluate("#if($name== 'over' ) over #else not over #end")
#if($name=='over')
over
#else
not over
#end
</body>
</html>

宏指令

作用:定义重用模块(可带参数)
定义语法

#macro(宏名[$arg]?)
...
#end

调用方法

$宏名([$arg]?)

示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
#macro($table $list)
    <table>
        $list
    </table>
#end

## 引用定义好的模块
    $table($list)
</body>
</html>
  • 4
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值