代码生成框架Velocity
Velocity是一个基于Java的模板引擎,用户可以使用模板语言VTL来引用由Java代码定义的对象。
Velocity通常可以作为动态生成页面而广泛使用,还是一种功能强大的代码生成工具。
Velocity模板类似于JSP文件,当客户端发送请求后,Velocity引擎江根据模板产生动态地页面。如果要使用Velocity生成动态页面,需要扩展VelocityServlet类来实现请求的处理,并通过handleRequest方法返回一个模板变量,Velocity会负责模板到页面的转换。
它还可以从模板产生SQL脚本、XML及Java代码等。
1)模板文件
扩展名为“.vm”,是一个文本文件。
2)Java程序
可以为VelocityServlet的子类。
例:
(1)helloworld.vm
##testassign#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 programassignTotal Price:$$totalPrice
(2)HelloWorldVTL.java
importjava.io.StringWriter;
importjava.io.Writer;
importjava.util.ArrayList;
importjava.util.Collection;
importjava.util.Iterator;
importorg.apache.velocity.Template;
importorg.apache.velocity.VelocityContext;
importorg.apache.velocity.app.Velocity;
publicclassHelloWorldVTL...{
publicstaticvoidmain(String[] args)throwsException...{
Velocity.init();
Template template=Velocity.getTemplate("./src/helloworld.vm");
VelocityContext ctx=newVelocityContext();
Collection products=newArrayList();
products.add(newProduct("Product 1",12.99));
products.add(newProduct("Product 2",13.99));
products.add(newProduct("Product 3",11.99));
ctx.put("productList", products);
Iterator itr=products.iterator();
doubletotal=0.00;
while(itr.hasNext())...{
Product p=(Product)itr.next();
total+=p.getPrice();
} ctx.put("totalPrice",newDouble(total));
Writer writer=newStringWriter();
template.merge(ctx, writer);
System.out.println(writer.toString());
}}
(3)Product.java
publicclassProduct...{
privateString name;
privatedoubleprice;
publicProduct(String name,doubleprice)...{
super();
this.name=name;
this.price=price;
}
publicString getName()...{
returnname;
}
publicvoidsetName(String name)...{
this.name=name;
}
publicdoublegetPrice()...{
returnprice;
}
publicvoidsetPrice(doubleprice)...{
this.price=price;
}}
输出:
2008-3-10 2:45:12 org.apache.velocity.runtime.log.JdkLogChute log
信息: FileResourceLoader : adding path '.'
2008-3-10 2:45:12 org.apache.velocity.runtime.log.JdkLogChute log
信息: Null reference [template './src/helloworld.vm', line 3, column 16] : $gan.shu.man cannot be resolved.
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
3)处理流程:
使用Velocity生成过程如下:
(1)初始化模板引擎;
(2)加载模板文件;
(3)创建模板上下文;
(4)给模板变量赋值;
(5)替换模板中的值生成代码。
通过模板生成代码是比较好的选择,模板在某种意义上来说就是配置文件的一种,当生成文件内容修改后,用户不需要修改源程序,只需要修改模板文件即可,提高了代码的可维护性。