First Velocity Demo

来源:互联网 发布:mt4模拟交易软件 编辑:程序博客网 时间:2024/06/10 15:57
转载自 http://www.blogjava.net/sxyx2008/
 
Java code

package com.velocity.test;
import java.io.IOException;
import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;


public class VelocityTest {

 public static void main(String[] args) {
  
  
  try {
   Velocity.init();
  } catch (Exception e) {
   e.printStackTrace();
  }
  
  VelocityEngine engine=new VelocityEngine();
  engine.setProperty(Velocity.RESOURCE_LOADER, "class");
  engine.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
  
  VelocityContext context= new VelocityContext();
  context.put("name", "林心如");
  context.put("velocity", "Velocity");
  
  Template template = null;
  try {
   template = engine.getTemplate("velocity.vm","gbk");
  } catch (ResourceNotFoundException e) {
   e.printStackTrace();
  } catch (ParseErrorException e) {
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }
  
  StringWriter writer=new StringWriter();
  
  try {
   template.merge(context, writer);
   System.out.println(writer.toString());
  } catch (ResourceNotFoundException e) {
   e.printStackTrace();
  } catch (ParseErrorException e) {
   e.printStackTrace();
  } catch (MethodInvocationException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

}


Velocity 模版
Hello $name ,
 this is my first $velocity !!!
#set($sex="女")
*******************************************
$sex
#**
 #set($a=true)
 
 #if($a)
  true
 #else
  false
 #end
 
 #set()
*#

Jar包支持
avalon-logkit-2.1.jar
commons-collections-3.2.1.jar
commons-lang-2.4.jar
oro-2.0.8.jar
velocity-1.6.3.jar
原创粉丝点击