Velocity通常可以作为动态生成页面而广泛使用,还是一种功能强大的代码生成工具。
Velocity模板类似于JSP文件,当客户端发送请求后,Velocity引擎江根据模板产生动态地页面。如果要使用Velocity生成动态页面,需要扩展VelocityServlet类来实现请求的处理,并通过handleRequest方法返回一个模板变量,Velocity会负责模板到页面的转换。
使用Velocity生成过程如下:
(1)初始化模板引擎;
(2)加载模板文件;
(3)创建模板上下文;
(4)给模板变量赋值;
(5)替换模板中的值生成代码。
1.为模板设置数据值
$treeList.get(1)
列表中的第二个元素。
2.VTL 支持一种静态引用符号,以避免呈现不存在的或者 空的
引用。如果使用安静引用符号,比如 $!notDeclared
,那么 Velocity 将什么也不输出,而不是输出完整的引用名。
3.可以使用指示符 #if... #then... #else....
有条件地呈现模板中特定的部分。(下面有例子)
4.使用 #foreach 循环(下面有例子)
##
开始,多行注释则放在 #*
和 *#
之间。例:
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