分享

Velocity是如何工作的

 贾朋亮博客 2015-05-29

当在一个应用程序或者servlet中使用Velocity的时候,你要做如下几个工作:

  1. 初始化VelocityVelocity提供2种使用形式,不管是单一实例模式还是单独运行实例模式,初始化过程都只做一次
  2. 创建上下文对象
  3. 添加数据对象到上下文中
  4. 选择模版
  5. 'Merge'模版并且执行数据输出

代码中,通过使用org.apache.velocity.app.Velocity类单一实例模式

复制代码
 1 import java.io.StringWriter;
 2 import org.apache.velocity.VelocityContext;
 3 import org.apache.velocity.Template;
 4 import org.apache.velocity.app.Velocity;
 5 import org.apache.velocity.exception.ResourceNotFoundException;
 6 import org.apache.velocity.exception.ParseErrorException;
 7 import org.apache.velocity.exception.MethodInvocationException;
 8 
 9 Velocity.init();
10 
11 VelocityContext context = new VelocityContext();
12 
13 context.put( "name", new String("Velocity") );
14 
15 Template template = null;
16 
17 try
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 
39 template.merge( context, sw );
复制代码

这是一个基本的形式,非常简单,对不对?这就是你在使用Velocity来呈现一个模版时所做的事情。你或许不需要像这样来写代码 - 我们提供了一些工具来更容易的使用它。无论如何,不管如何使用Velocity,上面的执行序列都是会在后台真实发生的。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多