Apache velocity is being used by developer to create dynamic string from predefine template.
Lets start with example directly.
Download below dependencies.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<dependencies> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.2</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> </dependencies> |
You can create Velocity object in two different ways.
1. Using Singleton class (More Preferable)
2. Create new instance of VelocityEngine using “new” keyword.
Template format :
Velocity template contains .vm as an extension. Please find below template example.vm
1 2 3 4 5 |
Below three values we are passing from java code. Sample Type: $sample Name : $siteName Visitor : $visitorPerPage |
Lets consider above template and start with below example.
Singleton
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
private static void singletonCreation() { Velocity.init(); VelocityContext context = new VelocityContext(); context.put("siteName", "omtlab.com"); context.put("visitorPerPage", "7777"); context.put("sample", "Singleton"); Template t = Velocity.getTemplate("example.vm"); StringWriter sw = new StringWriter(); t.merge(context, sw); System.out.println(sw.toString()); } |
Create multiple objects
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
private static void multipleObjects() { VelocityEngine ve = new VelocityEngine(); ve.init(); VelocityContext context = new VelocityContext(); context.put("siteName", "omtlab.com"); context.put("visitorPerPage", "7777"); context.put("sample", "Multiple Objects"); Template t = ve.getTemplate("example.vm"); StringWriter sw = new StringWriter(); t.merge(context, sw); System.out.println(sw.toString()); } |
Use Of Velocity Methods
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private static void templateWithinVelocity() { Velocity.init(); VelocityContext context = new VelocityContext(); context.put("siteName", "omtlab.com"); context.put("visitorPerPage", "7777"); context.put("sample", "Template Within Velocity"); StringWriter sw = new StringWriter(); Velocity.mergeTemplate("example.vm", context, sw); System.out.println(sw.toString()); } |