Velocity

Velocity是一个基于 Java 的模板引擎,用户可以使用模板语言VTL来引用由Java代码定义的对象。
Velocity通常可以作为动态生成页面而广泛使用,还是一种功能强大的代码生成工具。

Velocity模板类似于JSP文件,当客户端发送请求后,Velocity引擎江根据模板产生动态地页面。如果要使用Velocity生成动态页面,需要扩展VelocityServlet类来实现请求的处理,并通过handleRequest方法返回一个模板变量,Velocity会负责模板到页面的转换。

使用Velocity生成过程如下:
(1)初始化模板引擎;
(2)加载模板文件;
(3)创建模板上下文;
(4)给模板变量赋值;
(5)替换模板中的值生成代码。

1.为模板设置数据值
#set ($name = "Tom")
#set($treelist = ["1","2","3","4"]) 可以使用  $treeList.get(1) 列表中的第二个元素。

2.VTL 支持一种静态引用符号,以避免呈现不存在的或者 空的引用。如果使用安静引用符号,比如 $!notDeclared,那么 Velocity 将什么也不输出,而不是输出完整的引用名。

3.可以使用指示符 #if... #then... #else....有条件地呈现模板中特定的部分。(下面有例子)

4.使用 #foreach 循环(下面有例子)

5.单行注释或者行尾注释从 ##开始,多行注释则放在 #*和 *#之间。

例:

1.helloworld.vm

##test assign 
#set($name = "gan.shu.man")
Employee name: $gan.shu.man

##test condition
#if($name == "gan.shu.man")
$name: very good!!
#else
$name: sorry!!
#end

Product information
##test circular
#foreach($product in $productList)
$product.Name    $$product.Price
#end

##test program assign
Total Price: $$totalPrice

2.Product.JAVA

public class Product {
private String name;
private double price;

//此处省略构造方法和getter,setter方法
}

3. VTL .JAVA

public class VTL {
public static void main(String[] args) {
Velocity.init();                          //初始化模版
 Template template = Velocity.getTemplate("./src/helloworld.vm"); //加载模版文件
 VelocityContext ctx = new VelocityContext(); //创建模版上下文

 Collection products = new ArrayList();
 products.add(new Product("Product 1",12.99));
 products.add(new Product("Product 2",13.99));
 products.add(new Product("Product 3",11.99));
 ctx.put("productList", products);
 Iterator itr = products.iterator();
 double total = 0.00;
 while(itr.hasNext()){
  Product p = (Product)itr.next();
  total+=p.getPrice();
 }
 ctx.put("totalPrice", new Double(total)); //给模版变量赋值
 Writer writer = new StringWriter();
 template.merge(ctx, writer);
 System.out.println(writer.toString());
}
}

输出:

Employee name: $gan.shu.man
gan.shu.man: very good!!
Product information
Product 1    $12.99
Product 2    $13.99
Product 3    $11.99
Total Price: $38.97









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值