Apache Velocity is a free, simple and powerful template engine written in 100% pure Java.
This requires the libraries velocity-1.7.jar, oro-2.0.8.jar, commons-lang-2.4.jar,
commons-collections-3.2.1.jar, commons-logging-1.1.jar, log4j-1.2.12.jar to be in classpath.
The following example shows invoking static and instance methods in Velocity.
/**
* Initialize engine and get template
*/
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
Template template = ve.getTemplate("methods.vm");
/**
* Prepare context data
*/
VelocityContext context = new VelocityContext();
context.put("bean", new MethodBean()); //for invoking instance methods
context.put("sys", System.class); //for invoking static methods
/**
* Merge data and template
*/
StringWriter swOut = new StringWriter();
template.merge(context, swOut);
System.out.println(swOut);
}
}
It gives the following output,
ABC
BE THE CODER
2 pow 3 : 8.0
OS Name : Windows XP
Temp Dir : C:\DOCUME~1\VSUDHA~1\LOCALS~1\Temp\
{java.runtime.name=Java(TM) SE Runtime Environment,
sun.boot.library.path=C:\Program Files\Java\jdk1.6.0_10\jre\bin,
java.vm.specification.vendor=Sun Microsystems Inc.,
....
....
user.variant=, os.name=Windows XP, sun.jnu.encoding=Cp1252,
sun.desktop=windows}