Apache velocity is a java based template engine. Imagine a situation where you have to generate a html page using java. One approach would be to do using a lot of string concatenation another could be using a jsp page and call the jsp page in web container and get the html response string. But these approach have some inherited problem, when we do string manipulation we need to do it in java code which need to recompile the java classes, and in jsp approach we have an overhead of calling http.
Velocity solves this problem. We write template file and send this template to velocity engine which read valued from java object and render the output according to the template.
Lets consider this with an example.
Download velocity jars from apache velocity site.
Add the ( velocity-1.6.3.jar, commons-collections-3.2.1.jar, commons-lang-2.4.jar, commons-logging-1.1.jar) jars in the classpath.
Create template file test.vm and put this file in src folder in any package(say template).
Here, we are iterating through the list and printing the values. Note that $testdata is the name that we have given while putting the instance of TestData class in VelocityContext and $testdata.header is same as $testdata.getHeader.
Create a databean class.
Create a main class with initialize the velocity engine and do the template translation.
Here properties p contains the engine configuration values. Here we put “file.resource.loader.class” which tells the velocity engine to look for template file in classpath and since we put the template file test.vm under src/template folder, the fully qualified name of template file would be “template/test.vm”. Next we populating the data bean and put the databean in the context object. Mark that the name given to databean is testdata which is same name that we used in vm file to access the object. We can assume that we are passing the TestData object to template file using testdata. Lastly we are merging context (which contains data) and template to generate the output.