Knowledge Walls
John Peter
Pune, Maharashtra, India
How to use Java Class in apache velocity template engine with Example
4557 Views
UserInfo.java
public class UserInfo{
    private int rollno;
    private String username;
    
    public int getRollno() {
        return rollno;
    }
    public void setRollno(int rollno) {
        this.rollno = rollno;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
}
ListOfClassRecordInVTLExample
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 ListOfClassRecordInVTLExample {
    public static void main(String args[]){
        VelocityEngine ve = new VelocityEngine();
        ve.init();
         
        Template t = ve.getTemplate("velocitytemplate.vm");
         
        VelocityContext vc = new VelocityContext();
        List<UserInfo> userInfoList = new ArrayList<UserInfo>();
        {
            UserInfo userinfo = new UserInfo();
            userinfo.setRollno(1001);
            userinfo.setUsername("Parthasarathy");
            
            userInfoList.add(userinfo);
        }
        {
            UserInfo userinfo = new UserInfo();
            userinfo.setRollno(1002);
            userinfo.setUsername("Gopal");
            
            userInfoList.add(userinfo);
        }
        {
            UserInfo userinfo = new UserInfo();
            userinfo.setRollno(1003);
            userinfo.setUsername("Lakshanya");
            
            userInfoList.add(userinfo);
        }
        {
            UserInfo userinfo = new UserInfo();
            userinfo.setRollno(1004);
            userinfo.setUsername("Vidhyaa");
            
            userInfoList.add(userinfo);
        }
        vc.put("user_info_list", userInfoList);
        
        StringWriter sw = new StringWriter();
        t.merge(vc, sw);
         
        System.out.println(sw);
    }
}
Velocitytemplate.vm 
User Details
------------
#foreach ($userinfo in $user_info_list)
RollNo: $userinfo.getRollno()
Username: $userinfo.getUsername()

#end
Output 
User Details
------------
RollNo: 1001
Username: Parthasarathy

RollNo: 1002
Username: Gopal

RollNo: 1003
Username: Lakshanya

RollNo: 1004
Username: Vidhyaa
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