In Apache velocity, There are three main ways to pass data from Java class to VM template.
1. Key and Value mapping
2. Key and Bean/POJO (Object) mapping
3. Key and Inner Map mapping
Lets see each and every mapping with example.
1. Key and Value mapping
This is normal key and value in VelocityContext. Find below VM and Code for example.
context.vm
1 2 |
Key : name Value : $name |
Java Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
private static void simpleKeyValueContext() { Velocity.init(); VelocityContext context = new VelocityContext(); context.put("name", "omtlab"); Template t = Velocity.getTemplate("context.vm"); StringWriter writer = new StringWriter(); t.merge(context, writer); System.out.println(writer.toString()); } |
2. Key and Bean/POJO (Object) mapping
beancontext.vm
1 2 3 4 5 6 7 |
Key : name Value : $name Customer Bean Name : $customerBean.name Customer Bean Company : $customerBean.getCompany() Customer Bean Method Call : $customerBean.getNameCompany() |
Customer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package com.omt.velocity; public class Customer { public Customer() { } private String name; private String company; public String getNameCompany() { return name + "|" + company; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } } |
Java Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
private static void beanInContext() { Velocity.init(); VelocityContext context = new VelocityContext(); Customer c = new Customer(); c.setName("Dhiral Pandya"); c.setCompany("omt"); context.put("customerBean", c); context.put("name", "omtlab"); Template t = Velocity.getTemplate("beancontext.vm"); StringWriter writer = new StringWriter(); t.merge(context, writer); System.out.println(writer.toString()); } |
3. Key and Inner Map mapping
innermapcontext.vm
1 |
Inner Value : $parentKey.innerMapKey |
Java Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
private static void innerMapContext() { Velocity.init(); VelocityContext context = new VelocityContext(); Map<String, String> map = new HashMap<>(); map.put("innerMapKey", "This is value from inner map"); context.put("parentKey", map); Template t = Velocity.getTemplate("innermapcontext.vm"); StringWriter writer = new StringWriter(); t.merge(context, writer); System.out.println(writer.toString()); } |