Knowledge Walls
John Peter
Pune, Maharashtra, India
How to use list object with foreach in Java Velocity Example
24614 Views
VelocityListExample
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class VelocityListExample {
    public static void main(String args[]) throws Exception {
        VelocityEngine engine = new VelocityEngine();
        engine.init();
        
        Template template = engine.getTemplate("userinfo.vm");
        
        VelocityContext vc = new VelocityContext();
        
        List<String> userList = new ArrayList<String>();
            userList.add("Bala");
            userList.add("Arun");
            userList.add("Chinna");
            userList.add("Vijay");
            
        vc.put("userList", userList);
        
        StringWriter writer = new StringWriter();
        template.merge(vc, writer);
        
        System.out.println(writer);
    }
}
Userinfo.vm 
User Details
------------
#foreach ($userName in $userList)
Name is. $userName
#end
Output 
User Details
------------
Name is. Bala
Name is. Arun
Name is. Chinna
Name is. Vijay
Best Lessons of "Java Apache Velocity Examples"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details