Apache Velocity Study

Velocity is java base template engine, you can map the java object to html file or text file. The output is defined in a template file. Your need velocity-1.7.jar and velocity-1.7-dep.jar files.

Below is an output html page.

Customer information for customer number ABC123

Name: Joe JavaRanch
Address: 123 Rancho Javo
City: Bueno Ranch
State: CO
Zip: 63121
Phone: 303-555-1212

The associated template code is velocitySearch.vm
<head><title>Customer Search Results - $customer.customerNumber</title></head>
<body bgcolor="#faf7f1">
    <h1>Customer information for customer number $customer.customerNumber</h1>
    <b>Name:</b> $customer.name<br>
    <b>Address:</b> $customer.address<br>
    <b>City:</b> $customer.city<br>
    <b>State:</b> $customer.state<br>
    <b>Zip:</b> $customer.zip<br>
    <b>Phone:</b> $customer.phone<br>

java files.

package velocitySearch;

public class Customer {
	String customerNumber;
    String name;
    String address;
    String city;
    String state;
    String zip;
    String phone;

    public String getCustomerNumber() {return customerNumber;}
    public void setCustomerNumber(String s) {customerNumber = s;}
    public String getName() {return name;}
    public void setName(String s) {name = s;}
    public String getAddress() {return address;}
    public void setAddress(String s) {address = s;}
    public String getCity() {return city;}
    public void setCity(String s) {city = s;}
    public String getState() {return state;}
    public void setState(String s) {state = s;}
    public String getZip() {return zip;}
    public void setZip(String s) {zip = s;}
    public String getPhone() {return phone;}
    public void setPhone(String s) {phone = s;}

package velocitySearch;
import org.apache.velocity.Template;
import java.io.StringWriter;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.VelocityContext;

public class CustomerSearch {

	public static void main(String[] args) {
	     CustomerSearch cs = new CustomerSearch(); 

	     StringWriter writer = cs.getTemplate(); 

	public StringWriter getTemplate()  {

        Template template = null;
        StringWriter writer = new StringWriter();
        Customer customer = getCustomer();
        VelocityContext context = new VelocityContext();
        try  {
            context.put("customer", customer);
            template = Velocity.getTemplate("src/velocitySearch.vm");
            template.merge(context, writer); 
        }  catch( Exception e )  {
          System.err.println("Exceptionht: " + e.getMessage());

        return writer;

    private Customer getCustomer()  {
        Customer customer = new Customer();
        customer.setName("Joe JavaRanch");
        customer.setAddress("123 Rancho Javo");
        customer.setCity("Bueno Ranch");
        return customer;

original source