Velocity is a Java-based template engine. It permits web page designers to reference methods defined in Java code. Basically, you can create files (HTML, XML, etc…) writing scripts and generate them following a template.
– Create Maven Project.
– Add dependency in your pom file – Change the version of the lib:
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.6.4</version>
</dependency>
– Create a Vm template, like this one. Save as .vm (I created outside the package test). So, place your template in Project > src > customer.vm and not with the code which the structure is: Project > src > package.test:
Hello $word! This is your first Velocity script !
– Create a Java Class called CreateScript:
import java.io.StringWriter;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
public class createXml {
public static void main(String[] args) throws Exception {
VelocityEngine ve = new VelocityEngine();
ve.init();
try {
Template t = ve.getTemplate("src/helloworld.vm");
VelocityContext context = new VelocityContext();
context.put("word", "World");
StringWriter writer = new StringWriter();
t.merge(context, writer);
System.out.println(writer.toString());
} catch (ResourceNotFoundException rnfe) {
System.out.println("Couldn't find the template");
} catch (ParseErrorException pee) {
System.out.println("syntax error: problem parsing the template");
} catch (MethodInvocationException mie) {
System.out.println("something invoked in the template");
System.out.println("threw an exception");
} catch (Exception e) {
}
}
}
– Vm file is the template, you will create the template and what the variables that will have the value that you want.
– Inside Java Class:
You need initialize the Velocity API – Write the path of the vm template – Initialize the context and write all the variables and the values (name – variable, word – value) – Initialize the Writer which will render the template – Merge the context and the values creating the template – Show the result
– To run the project, first I had to compil with maven test and after this I just choose Run As – Java Application.
So, this is the first script, I will write more about, but between this you can have a look on the links below. See you guys 🙂
Sources:
http://velocity.apache.org/engine/devel/developer-guide.html
https://velocity.apache.org/engine/releases/velocity-1.5/webapps.html
http://www.javaranch.com/journal/2004/03/Velocity-AnIntroduction.html
http://www.javaworld.com/article/2075966/core-java/start-up-the-velocity-template-engine.html