Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
In this article, I present a short primer on the Velocity Template Engine and its template language, Velocity Template Language (VTL). I also demonstrate how to use Velocity through several examples.
No explanation of a programming-related subject would be complete without a Hello World example. Any application using Velocity
requires two parts. The first is the template, which in this example is a file called helloworld.vm:
Hello $name! Welcome to Velocity!
The second is a corresponding Java program called 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( "helloworld.vm" );
/* create a context and add data */
VelocityContext context = new VelocityContext();
context.put("name", "World");
/* now render the template into a StringWriter */
StringWriter writer = new StringWriter();
t.merge( context, writer );
/* show the World */
System.out.println( writer.toString() );
}
}
Now, when you compile and run this program, you will see the output:
Hello World! Welcome to Velocity!
This is a trivial example, but it contains the crucial pieces to give you an idea of what Velocity templating is all about.
Designed as an easy-to-use general templating tool, Velocity is useful in any Java application area that requires data formatting and presentation. You should use Velocity for the following reasons:
The last point is important -- it means that you can reuse your existing classes. So, objects you want to use in your templates don't need to be structured in a certain way, like JavaBeans, or implement special I/O or lifecycle modes, such as JSP (JavaServer Pages) taglibs. The only requirement is that methods are public. You will see more of this when we cover the template language in detail.