zoukankan      html  css  js  c++  java
  • Velocity是如何工作的

    当在一个应用程序或者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,上面的执行序列都是会在后台真实发生的。

  • 相关阅读:
    Nginx安装配置
    HTTPS原理(三次握手)
    Linux常用指令
    MVC思想
    MySQL简介
    PHP面向对象(二)
    PHP面向对象(一)
    php循环用法
    如何删掉git版本库master分支的第一个commit
    韦东山嵌入式Linux学习笔记08--中断体系结构
  • 原文地址:https://www.cnblogs.com/treerain/p/velocity_how_to_work.html
Copyright © 2011-2022 走看看