基本模式
当你在一个应用程序或者一个servlet里,或者在其他任何一个地方使用Velocity时,通常按照如下方式处理:
初始化Velocity。Velocity可以使用两种模式,作为“单独的运行时实例”的单例模式(在下面的内容会介绍),你仅仅只需要初始化一次。创建一个Context对象(后面会介绍这是什么)。把你的数据对象添加到Context(上下文)。选择一个模板。‘合并’ 模板和你的数据输出。在代码里通过org.apache.velocity.app.Velocity类使用单例模式,代码如下:
01 import java.io.StringWriter; 02 import org.apache.velocity.VelocityContext; 03 import org.apache.velocity.Template; 04 import org.apache.velocity.app.Velocity; 05 import org.apache.velocity.exception.ResourceNotFoundException; 06 import org.apache.velocity.exception.ParseErrorException; 07 import org.apache.velocity.exception.MethodInvocationException; 08 09Velocity.init(); 10 11 VelocityContext context = new VelocityContext(); 12 13 context.put( "name", new String("Velocity") ); 14 15 Template template = null; 16 17try 18{ 19 template = Velocity.getTemplate("mytemplate.vm"); 20} 21 catch( ResourceNotFoundException rnfe ) 22{ 23 // couldn't find the template 24} 25 catch( ParseErrorException pee ) 26{ 27 // syntax error: problem parsing the template 28} 29 catch( MethodInvocationException mie ) 30{ 31 // something invoked in the template 32 // threw an exception 33} 34 catch( Exception e ) 35{} 36 37 StringWriter sw = new StringWriter(); 38 39template.merge( context, sw );这是个基本的模式,它非常简单,不是吗?当你使用Velocity渲染一个模板的时候,通常会发生什么。你可能不会完全像这样写代码,所以我们提供几个工具类帮助你写代码。然而, 无论如何,按照上面的序列使用Velocity,它向我们展示了台前幕后发生了什么。
转载自 并发编程网 - ifeve.com 相关资源:Velocity1.4 学习指南中文版