Velocity是一个基于Java的模板引擎,用户可以使用模板语言VTL来引用由Java代码定义的对象。

Velocity通常可以作为动态生成页面而广泛使用,还是一种功能强大的代码生成工具。
Velocity模板类似于JSP文件,当客户端发送请求后,Velocity引擎江根据模板产生动态地页面。如果要使用Velocity生成动态页面,需要扩展VelocityServlet类来实现请求的处理,并通过handleRequest方法返回一个模板变量,Velocity会负责模板到页面的转换。
它还可以从模板产生SQL脚本、XML及Java代码等。
1)模板文件
扩展名为“.vm”,是一个文本文件。
2)Java程序
可以为VelocityServlet的子类。
例:
(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)HelloWorldVTL.java

import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
public class HelloWorldVTL {
 public static void main(String[] args) throws Exception{
  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());
 }

}


 

(3)Product.java

public class Product {
 private String name;
 private double price;
 public Product(String name, double price) {
  super();
  this.name = name;
  this.price = price;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public double getPrice() {
  return price;
 }

 public void setPrice(double price) {
  this.price = price;