Second script with Velocity (VM)

Hi guys, Today I will post another example of VM template, sorry for not to post something new, but I’ve got flu this week, I am feeling like a zombie ūüė¶

This example is more complete and I have tested, so it is working ūüėÄ I just made some changes to print the result with the values and the template. We have get and set methods, the vm template in html and the class to set the values and merge the template.

– Create the get and set customer class:

package test;
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;}

– Create a customer search class which will set the values and merge with the template:

package test;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import test.Customer;

public class CustomerSearch  {
    public static void main(String[] args) throws Exception { 

     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/customer.vm");
            template.merge(context, writer); 
        }  catch( Exception e )  {
          System.err.println("Exception caught: " + 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;

– After, create the vm template html:

<head><title>Customer Search Results - $customer.customerNumber</title></head>
<body bgcolor="#faf7f1">
    <h1>Customer information for customer number $customer.customerNumber</h1>
    <b>Name:</b> $<br>
    <b>Address:</b> $customer.address<br>
    <b>City:</b> $<br>
    <b>State:</b> $customer.state<br>
    <b>Zip:</b> $<br>
    <b>Phone:</b> $<br>

Cheers guys !


First script with Velocity (VM)

Velocity is a Java-based template engine. It permits web page designers to reference methods defined in Java code. Basically, you can create files (HTML, XML, etc…) writing scripts and generate them following a template.


РCreate Maven Project.

– Add dependency in your pom file – Change the version of the lib:







РCreate a Vm template, like this one. Save as .vm (I created outside the package test). So, place your template in Project > src > customer.vm and not with the code which the structure is: Project > src > package.test:

Hello $word! This is your first Velocity script !


– Create a Java Class called CreateScript:

import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;

public class createXml {
   public static void main(String[] args) throws Exception {
   VelocityEngine ve = new VelocityEngine();

   try {
    Template t = ve.getTemplate("src/helloworld.vm");

    VelocityContext context = new VelocityContext();
    context.put("word", "World");
    StringWriter writer = new StringWriter();
    t.merge(context, writer);
    } catch (ResourceNotFoundException rnfe) {
      System.out.println("Couldn't find the template");
    } catch (ParseErrorException pee) {
      System.out.println("syntax error: problem parsing the template");
    } catch (MethodInvocationException mie) {
      System.out.println("something invoked in the template");
      System.out.println("threw an exception");
    } catch (Exception e) {

– Vm file is the template, you will create the template and what the variables that will have the value that you want.

– Inside Java Class:

You need initialize the Velocity API РWrite the path of the vm template РInitialize the context and write all the variables and the values (name Рvariable, word Рvalue) РInitialize the Writer which will render the template РMerge the context and the values creating the template РShow the result

– To run the project, first I had to compil with maven test and after this I just choose Run As –¬†Java Application.

So, this is the first script, I will write more about, but between this you can have a look on the links below. See you guys ūüôā