Apache Velocity Sample Code
First create the project & include the required jars like shown below -
First create the project & include the required jars like shown below -
Now create the below files in the package named 'templates' & as shown in figure above -
Accessories.vm
#set($directive.foreach.counter.initial.value = 1)
#foreach($lap in $accessories.lapList)
Laptop : $lap
#if($lap == "Lenovo")
Inside If
$accessories.laptops.put($lap, 46000)
#end
Price : $!accessories.laptops.get($lap)
$velocityCount
#end
#if($accessories.laptops.get($lap))
Laptop : $accessories.laptops.get($lap)
#else
Laptop : No Entry
#end
Iterating through the Map values
#foreach($map in $accessories.laptops)
Price : $map
#end
Person.vm
Name : $person.name
City : $person.city
Country : $person.country
#set($person.list = ["A","B"])
List : $person.list.get(0)
#if($person.list.get(0) == "A")
#set($person.city = "Bombay")
#else
#set($person.city = "null")
#end
New City : $person.city
#macro(findCity $chg)
#literal()
#if($person.city == "Bombay" && $chg)
#set($person.city = "Pune")
#end
#end
#set($person.city = $chg)
#end
#set($chg = "Pune")
#findCity($chg)
City Changed : $chg
Latest City : $person.city
helloworld.vm
Hello $name! Welcome to Velocity!
#set($what = $name)
Created By - ${person.name}
#include("txtfiles/Included1.txt", "txtfiles/Included2.txt") & used \#include()
Below Person information is from Person.vm file & to include that file have used \#parse()
#parse("templates/Person.vm")
#literal()
#*If dont comment this line then will get the error*#
#foreach($some in $more)
This is a multiline comment
#end
#end
#*Below macro can be created here also though it is defined in included template also but macro in included template is
not visible here *#
#macro(findCity $chg)
#set($person.city = $chg)
#end
#parse("templates/Accessories.vm")
#set($chg = "Noida")
#findCity($chg)
City in helloworld.vm : $person.city
#stop
It will not be rendered
Create below text file in the folder named 'txtfiles'
Included1.txt
This is included1.txt file
Included2.txt
This is included2.txt file
Now create the below java classes in package named 'utilities'
Accessories .java
package utilities;
import java.util.Map;
import java.util.List;
public class Accessories {
private Map<String, Integer> laptops;
private Map<String, Integer> mobiles;
private Map<Map<String, Integer>, Integer> packages;
private List<String> lapList;
private List<String> mobList;
public Map<String, Integer> getLaptops() {
return laptops;
}
public void setLaptops(Map<String, Integer> laptops) {
this.laptops = laptops;
}
public Map<String, Integer> getMobiles() {
return mobiles;
}
public void setMobiles(Map<String, Integer> mobiles) {
this.mobiles = mobiles;
}
public Map<Map<String, Integer>, Integer> getPackages() {
return packages;
}
public void setPackages(Map<Map<String, Integer>, Integer> packages) {
this.packages = packages;
}
public List<String> getLapList() {
return lapList;
}
public void setLapList(List<String> lapList) {
this.lapList = lapList;
}
public List<String> getMobList() {
return mobList;
}
public void setMobList(List<String> mobList) {
this.mobList = mobList;
}
}
Person.java
package utilities;
import java.util.ArrayList;
import java.util.List;
public class Person {
private String name;
private int age;
private String dob;
private String city;
public String country;
public ArrayList list;
public ArrayList getList(){
return list;
}
public void setList(List list){
this.list = (ArrayList) list;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public void setCity(String city){
this.city = city;
}
public String getCity(){
return city;
}
public String getCountry(){
return country;
}
public String isCity(){
return "Yes it is a city in Uttar Pradesh";
}
}
Now we create the main class named HelloWorld.java in 'consumers' package -
package consumers;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import utilities.Accessories;
import utilities.Person;
public class HelloWorld
{
public static void main( String[] args )
throws Exception
{
Person person = new Person();
person.setName("Nitin Agrawal");
person.country = "India";
person.setCity("Bareilly");
Accessories acc = new Accessories();
Map<String, Integer> laps = new HashMap<>();
laps.put("Dell Inspiron15R", 40500);
laps.put("Lenovo", 45000);
List<String> lapList = new ArrayList<>();
lapList.add("Lenovo");
lapList.add("Dell Inspiron15R");
acc.setLapList(lapList);
acc.setLaptops(laps);
/* first, get and initialize an engine */
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
/* create a context and add data */
VelocityContext context = new VelocityContext();
context.put("name", "World");
context.put("person", person);
context.put("accessories", acc);
/* next, get the Template */
Template t = ve.getTemplate( "templates/helloworld.vm" );
// Template t = ve.getTemplate( "templates/Person.vm" );
/* now render the template into a StringWriter */
StringWriter writer = new StringWriter();
t.merge( context, writer );
/* show the World */
System.out.println( writer.toString() );
}
}
After execution of the above class we get the below output -
Hello World! Welcome to Velocity!
Created By - Nitin Agrawal
This is included1.txt file
This is included2.txt file & used #include()
Below Person information is from Person.vm file & to include that file have used #parse()
Name : Nitin Agrawal
City : Bareilly
Country : India
List : A
New City : Bombay
City Changed : Pune
Latest City : Pune
*#
#foreach($some in $more)
This is a multiline comment
#end
Laptop : Lenovo
Inside If
45000
Price : 46000
1
Laptop : Dell Inspiron15R
Price : 40500
2
Laptop : No Entry
Iterating through the Map values
Price : 46000
Price : 40500
City in helloworld.vm : Noida
Please try it on your system & try different cases/ways to get better understanding of Velocity, its easy :) And in case of any issue please let me know, will be happy if I can further help :)
Accessories.vm
#set($directive.foreach.counter.initial.value = 1)
#foreach($lap in $accessories.lapList)
Laptop : $lap
#if($lap == "Lenovo")
Inside If
$accessories.laptops.put($lap, 46000)
#end
Price : $!accessories.laptops.get($lap)
$velocityCount
#end
#if($accessories.laptops.get($lap))
Laptop : $accessories.laptops.get($lap)
#else
Laptop : No Entry
#end
Iterating through the Map values
#foreach($map in $accessories.laptops)
Price : $map
#end
Person.vm
Name : $person.name
City : $person.city
Country : $person.country
#set($person.list = ["A","B"])
List : $person.list.get(0)
#if($person.list.get(0) == "A")
#set($person.city = "Bombay")
#else
#set($person.city = "null")
#end
New City : $person.city
#macro(findCity $chg)
#literal()
#if($person.city == "Bombay" && $chg)
#set($person.city = "Pune")
#end
#end
#set($person.city = $chg)
#end
#set($chg = "Pune")
#findCity($chg)
City Changed : $chg
Latest City : $person.city
helloworld.vm
Hello $name! Welcome to Velocity!
#set($what = $name)
Created By - ${person.name}
#include("txtfiles/Included1.txt", "txtfiles/Included2.txt") & used \#include()
Below Person information is from Person.vm file & to include that file have used \#parse()
#parse("templates/Person.vm")
#literal()
#*If dont comment this line then will get the error*#
#foreach($some in $more)
This is a multiline comment
#end
#end
#*Below macro can be created here also though it is defined in included template also but macro in included template is
not visible here *#
#macro(findCity $chg)
#set($person.city = $chg)
#end
#parse("templates/Accessories.vm")
#set($chg = "Noida")
#findCity($chg)
City in helloworld.vm : $person.city
#stop
It will not be rendered
Create below text file in the folder named 'txtfiles'
Included1.txt
This is included1.txt file
Included2.txt
This is included2.txt file
Now create the below java classes in package named 'utilities'
Accessories .java
package utilities;
import java.util.Map;
import java.util.List;
public class Accessories {
private Map<String, Integer> laptops;
private Map<String, Integer> mobiles;
private Map<Map<String, Integer>, Integer> packages;
private List<String> lapList;
private List<String> mobList;
public Map<String, Integer> getLaptops() {
return laptops;
}
public void setLaptops(Map<String, Integer> laptops) {
this.laptops = laptops;
}
public Map<String, Integer> getMobiles() {
return mobiles;
}
public void setMobiles(Map<String, Integer> mobiles) {
this.mobiles = mobiles;
}
public Map<Map<String, Integer>, Integer> getPackages() {
return packages;
}
public void setPackages(Map<Map<String, Integer>, Integer> packages) {
this.packages = packages;
}
public List<String> getLapList() {
return lapList;
}
public void setLapList(List<String> lapList) {
this.lapList = lapList;
}
public List<String> getMobList() {
return mobList;
}
public void setMobList(List<String> mobList) {
this.mobList = mobList;
}
}
Person.java
package utilities;
import java.util.ArrayList;
import java.util.List;
public class Person {
private String name;
private int age;
private String dob;
private String city;
public String country;
public ArrayList list;
public ArrayList getList(){
return list;
}
public void setList(List list){
this.list = (ArrayList) list;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public void setCity(String city){
this.city = city;
}
public String getCity(){
return city;
}
public String getCountry(){
return country;
}
public String isCity(){
return "Yes it is a city in Uttar Pradesh";
}
}
Now we create the main class named HelloWorld.java in 'consumers' package -
package consumers;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import utilities.Accessories;
import utilities.Person;
public class HelloWorld
{
public static void main( String[] args )
throws Exception
{
Person person = new Person();
person.setName("Nitin Agrawal");
person.country = "India";
person.setCity("Bareilly");
Accessories acc = new Accessories();
Map<String, Integer> laps = new HashMap<>();
laps.put("Dell Inspiron15R", 40500);
laps.put("Lenovo", 45000);
List<String> lapList = new ArrayList<>();
lapList.add("Lenovo");
lapList.add("Dell Inspiron15R");
acc.setLapList(lapList);
acc.setLaptops(laps);
/* first, get and initialize an engine */
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
/* create a context and add data */
VelocityContext context = new VelocityContext();
context.put("name", "World");
context.put("person", person);
context.put("accessories", acc);
/* next, get the Template */
Template t = ve.getTemplate( "templates/helloworld.vm" );
// Template t = ve.getTemplate( "templates/Person.vm" );
/* now render the template into a StringWriter */
StringWriter writer = new StringWriter();
t.merge( context, writer );
/* show the World */
System.out.println( writer.toString() );
}
}
After execution of the above class we get the below output -
Hello World! Welcome to Velocity!
Created By - Nitin Agrawal
This is included1.txt file
This is included2.txt file & used #include()
Below Person information is from Person.vm file & to include that file have used #parse()
Name : Nitin Agrawal
City : Bareilly
Country : India
List : A
New City : Bombay
City Changed : Pune
Latest City : Pune
*#
#foreach($some in $more)
This is a multiline comment
#end
Laptop : Lenovo
Inside If
45000
Price : 46000
1
Laptop : Dell Inspiron15R
Price : 40500
2
Laptop : No Entry
Iterating through the Map values
Price : 46000
Price : 40500
City in helloworld.vm : Noida
Please try it on your system & try different cases/ways to get better understanding of Velocity, its easy :) And in case of any issue please let me know, will be happy if I can further help :)