Hello $name! Welcome to $site world!
HelloWorld.java就是处理程序了,其中注释写的很清楚了,下面是HelloWorld.java的代码:
import java.io.StringWriter;import org.apache.velocity.app.VelocityEngine;import org.apache.velocity.Template;import org.apache.velocity.VelocityContext;public class HelloWorld {public static void main(String[] args) throws Exception {/* first, get and initialize an engine */VelocityEngine ve = new VelocityEngine();ve.init();/* next, get the Template */Template t = ve.getTemplate("hellosite.vm");/* create a context and add data */VelocityContext context = new VelocityContext();context.put("name", "xuwei");context.put("site", "http://blog.iyunv.com/xw13106209");/* now render the template into a StringWriter */StringWriter writer = new StringWriter();t.merge(context, writer);/* show the World */System.out.println(writer.toString());}} 3.2.实例2
这里模板和实例1的相同,java代码有所不如,代码如下。
import java.io.StringWriter;import org.apache.velocity.app.VelocityEngine;import org.apache.velocity.Template;import org.apache.velocity.VelocityContext;public class HelloWorld2 {public static void main(String[] args) throws Exception {// 初始化Velocity模板引擎VelocityEngine ve = new VelocityEngine();ve.init("D:\\Documents\\workspace\\VelocityTest\\a.properties");// Velocity获取模板文件,得到模板引用Template t = ve.getTemplate("hellosite.vm");// 初始化环境,并将数据放入环境VelocityContext context = new VelocityContext();context.put("name", "xuwei");context.put("site", "http://blog.iyunv.com/xw13106209");// 将环境变量和输出部分结合StringWriter writer = new StringWriter();t.merge(context, writer);System.out.println(writer.toString());}} 在这里,配置文件主要的作用就是提供a.properties文件的路径,不多说了,下面是a.properties的代码:
runtime.log = velocity_example.loginput.encoding=gbk output.encoding=gbk file.resource.loader.path=D:\\Documents\\workspace\\VelocityTest