HashMapForeachVelocityExample
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
public class HashMapForeachVelocityExample {
public static void main(String args[]) throws Exception {
Map<String,String> userDataMap = new HashMap<String,String>();
userDataMap.put("1001", "Sarathy");
userDataMap.put("1002", "Kumar");
userDataMap.put("1003", "Raja");
userDataMap.put("1004", "Gopal");
VelocityEngine engine = new VelocityEngine();
engine.init();
Template template = engine.getTemplate("userinfo.vm");
VelocityContext vc = new VelocityContext();
vc.put("userDataMap", userDataMap);
StringWriter writer = new StringWriter();
template.merge(vc, writer);
System.out.println(writer);
}
}
|
Userinfo.vm
User Details
------------
#foreach ($rno in $userDataMap.keySet())
Rno is. $rno; Name is $userDataMap[$rno] or Name is $userDataMap.get($rno)
#end
|
Output
User Details
------------
Rno is. 1003; Name is Raja or Name is Raja
Rno is. 1004; Name is Gopal or Name is Gopal
Rno is. 1001; Name is Sarathy or Name is Sarathy
Rno is. 1002; Name is Kumar or Name is Kumar
|