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

来源:互联网 发布:p图滤镜软件 编辑:程序博客网 时间:2024/06/06 05:13

基本模式

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

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

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

01import java.io.StringWriter;
02import org.apache.velocity.VelocityContext;
03import org.apache.velocity.Template;
04import org.apache.velocity.app.Velocity;
05import org.apache.velocity.exception.ResourceNotFoundException;
06import org.apache.velocity.exception.ParseErrorException;
07import org.apache.velocity.exception.MethodInvocationException;
08 
09Velocity.init();
10 
11VelocityContext context = new VelocityContext();
12 
13context.put( "name"new String("Velocity") );
14 
15Template template = null;
16 
17try
18{
19   template = Velocity.getTemplate("mytemplate.vm");
20}
21catch( ResourceNotFoundException rnfe )
22{
23   // couldn't find the template
24}
25catch( ParseErrorException pee )
26{
27  // syntax error: problem parsing the template
28}
29catch( MethodInvocationException mie )
30{
31  // something invoked in the template
32  // threw an exception
33}
34catch( Exception e )
35{}
36 
37StringWriter sw = new StringWriter();
38 
39template.merge( context, sw );

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

原创文章,转载请注明: 转载自并发编程网 – ifeve.com

0 0
原创粉丝点击