java代码:
package org.weib.velocity;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.weib.velocity.bean.Person;
public class VelocityTest {/*
*//**
* 主函数
* @param args
*/
public static void main(String[] args)
{
//获取模板引擎
VelocityEngine ve = new VelocityEngine();
//模板文件所在的路径
String path = "C:\\J2EE\\workspace\\WebWorkProject\\WebContent\\";
//设置参数
ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
//处理中文问题
ve.setProperty(Velocity.INPUT_ENCODING,"GBK");
ve.setProperty(Velocity.OUTPUT_ENCODING,"GBK");
try
{
//初始化模板
ve.init();
//获取模板(hello.html)
//Velocity模板的名称
Template template = ve.getTemplate("hello.vm");
//获取上下文
VelocityContext context = new VelocityContext();
//把数据填入上下文
context.put("name","01"); // (注意:与上面的对应)
context.put("value","test");
//pojo
Person p = new Person();
p.setAge(10);
p.setName("weib");
p.setSex("m");
context.put("person",p);
VelocityContext context1 = new VelocityContext(context);
context1.put("name","contenxt2");
//输出路径
String outpath = "C://helloworld.html";
//输出
Writer wr = new PrintWriter(new FileOutputStream( new File(outpath)));
template.merge(context1, wr);
wr.flush();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
vm文件:
<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
</HEAD>
<BODY>
hello,$name! $value (注意:这里的name与VelocityTest.java中的名称要一致)
#if( ($name !="01") && ($name !="02"))
name =01
#end
<p>
<h2>Pojo</h2>
$person.getName();
$person.getSex();
$person.getAge();
<p>
<h2>arraylist</h2>
#set ($per =1)
per=$per
#set ($perstr ="123")
perstr= $perstr
</BODY>
</HTML>