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", "Eiffel Qiu"); context.put("site", "http://www.eiffelqiu.com"); /* now render the template into a StringWriter */ StringWriter writer = new StringWriter(); t.merge( context, writer ); /* show the World */ System.out.println( writer.toString() ); } }
将这两个文件放在同一个目录下,编译运行,结果是:
Hello Eiffel Qiu! Welcome to http://www.eiffelqiu.com world