Velocity入门

  
    Velocity是一基于java语言的模板引擎, 使用这个简单、功能强大的开发工具,可以很容易的将数据对象灵活的与格式化文档组装到一起。
 下面写一个简单的入门例子:

1. 模版文件

  1. Hello $name! Welcome to $site world!  

2. 测试代码

  1. package com.lht.velocity;   
  2.   
  3. import java.io.StringWriter;   
  4. import org.apache.velocity.app.VelocityEngine;   
  5. import org.apache.velocity.Template;   
  6. import org.apache.velocity.VelocityContext;   
  7. public class HelloWorld{   
  8.  public static void main( String[] args )throws Exception{   
  9.   /* first, get and initialize an engine */  
  10.   VelocityEngine ve = new VelocityEngine();   
  11.   ve.init();   
  12.   /* next, get the Template */  
  13.   Template t = ve.getTemplate( "hello.vm" );   
  14.   /* create a context and add data */  
  15.   VelocityContext context = new VelocityContext();   
  16.   context.put("name""VerRan");   
  17.   context.put("site""http://verran.iteye.com");   
  18.   /* now render the template into a StringWriter */  
  19.   StringWriter writer = new StringWriter();   
  20.   t.merge( context, writer );   
  21.   /* show the World */  
  22.   System.out.println( writer.toString() );    
  23.  }   
  24. }   
  25.   

3. 输出结果

  1. Hello VerRan! Welcome to http://verran.iteye.com world!  

注意:

将vm文件放置在项目的根目录下,否则会找不到文件。

续: 循环、判断的使用

  1. #set( $this = "Velocity")   
  2.   
  3. $this is great!   
  4.   
  5. #foreach( $name in $list )   
  6.     $name is great!   
  7. #end   
  8.   
  9. #set( $condition = true)   
  10.   
  11. #if ($condition)   
  12.     The condition is true!   
  13. #else   
  14.     The condition is false!   
  15. #end  


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值