Velocity官方指南-Velocity是如何工作的

原文网址  译者:方腾飞

基本模式

当你在一个应用程序或者一个servlet里,或者在其他任何一个地方使用Velocity时,通常按照如下方式处理:

  1. 初始化Velocity。Velocity可以使用两种模式,作为“单独的运行时实例”的单例模式(在下面的内容会介绍),你仅仅只需要初始化一次。
  2. 创建一个Context对象(后面会介绍这是什么)。
  3. 把你的数据对象添加到Context(上下文)。
  4. 选择一个模板。
  5. ‘合并’ 模板和你的数据输出。

在代码里通过org.apache.velocity.app.Velocity类使用单例模式,代码如下:


import java.io.StringWriter;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.MethodInvocationException;

Velocity.init();

VelocityContext context = new VelocityContext();

context.put( "name", new String("Velocity") );

Template template = null;

try
{
   template = Velocity.getTemplate("mytemplate.vm");
}
catch( ResourceNotFoundException rnfe )
{
   // couldn't find the template
}
catch( ParseErrorException pee )
{
  // syntax error: problem parsing the template
}
catch( MethodInvocationException mie )
{
  // something invoked in the template
  // threw an exception
}
catch( Exception e )
{}

StringWriter sw = new StringWriter();

template.merge( context, sw );


这是个基本的模式,它非常简单,不是吗?当你使用Velocity渲染一个模板的时候,通常会发生什么。你可能不会完全像这样写代码,所以我们提供几个工具类帮助你写代码。然而, 无论如何,按照上面的序列使用Velocity,它向我们展示了台前幕后发生了什么。 

上一篇:SQL Server 多实例下的复制


下一篇:Domino8.5服务器迁移方案