代码生成框架Velocity Velocity是一个基于Java的模板引擎,用户可以使用模板语言VTL来引用由Java代码定义的对象。 Velocity通常可以作为动态生成页面而广泛使用,还是一种功能强大的代码生成工具。 Velocity模板类似于JSP文件,当客户端发送请求后,Velocity引擎江根据模板产生动态地页面。如果要使用Velocity生成动态页面,需要扩展VelocityServlet类来实现请求的处理,并通过handleRequest方法返回一个模板变量,Velocity会负责模板到页面的转换。 它还可以从模板产生SQL脚本、XML及Java代码等。 1)模板文件 扩展名为“.vm”,是一个文本文件。 2)Java程序 可以为VelocityServlet的子类。 例: (1) Java代码 1. ##test assign 2. #set($name = "") 3. Employee name: $ 4. 5. ##test condition 6. #if($name == "") 7. $name: very good!! 8. #else 9. $name: sorry!! 10. #end 11. 12. Product information 13. ##test circular 14. #foreach($product in $productList) 15. $ $$ 16. #end 17. 18. ##test program assign 19. Total Price: $$totalPrice (2) Java代码 1. 2. 3. 4. import import import import 5. import 6. 7. import 8. import 9. import 10. public 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. } (3) Java代码 class HelloWorldVTL { public static void main(String[] args) throws Exception{ (); Template template = ("./src/"); VelocityContext ctx = new VelocityContext(); Collection products = new ArrayList(); (new Product("Product 1",); (new Product("Product 2",); (new Product("Product 3",); ("productList", products); Iterator itr = (); double total = ; while()){ Product p = (Product)(); total+=(); } ("totalPrice", new Double(total)); Writer writer = new StringWriter(); (ctx, writer); } class Product { private String name; private double price; public Product(String name, double price) { super(); = name; = price; } public String getName() { return name; } public void setName(String name) { = name; 1. public 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. } } public } public } double getPrice() { return price; void setPrice(double price) { = price; 输出: 2008-3-10 2:45:12 log 信息: FileResourceLoader : adding path '.' 2008-3-10 2:45:12 log 信息: Null reference [template './src/', line 3, column 16] : $ cannot be resolved. Employee name: $ very good!! Product information Product 1 $ Product 2 $ Product 3 $ Total Price: $ 3)处理流程: 使用Velocity生成过程如下: (1)初始化模板引擎; (2)加载模板文件; (3)创建模板上下文; (4)给模板变量赋值; (5)替换模板中的值生成代码。 通过模板生成代码是比较好的选择,模板在某种意义上来说就是配置文件的一种,当生成文件内容修改后,用户不需要修改源程序,只需要修改模板文件即可,提高了代码的可维护性。 本文来源:https://www.wddqw.com/doc/c5b742a63b68011ca300a6c30c2259010302f34b.html