1、建一個工程,把包導入(這裏應用的1.6)
2、創建一個含有main方法的類
import java.io.IOException;
import java.io.StringWriter;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
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 TestTemplateTheory {
/**
* @param args
*/
public static void main(String[] args) {
try {
//初始化velocity引擎
VelocityEngine ve = new VelocityEngine();
ve.init();
//獲取模板
Template template = ve.getTemplate("test1.vm");
//填充數據
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("myname", "姚明");
velocityContext.put("yourname", "麥迪");
//合併數據
StringWriter writer = new StringWriter();
template.merge( velocityContext, writer );
//顯示
System.out.println(writer.toString());
System.out.println(template);
} catch (ResourceNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseErrorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MethodInvocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3、和main類同一個目錄下見一個模板文件test1.vm
內容如下
<html>
<body>
#set($foo = "velocity")
Hello $foo world;
My name is $myname
Your name is $yourname
</body>
</html>
4、運行main方法,控制檯會打印出生成的html內容
<html>
<body>
Hello velocity world;
My name is 姚明
Your name is 麥迪
</body>
</html>