Calculation Example
This Example shows,
how to calculate using velocity. This code displays the product name and
their price with the total amount of all product.
Here in this code we have used method init() to initialize velocity,
then create file template named "Product.vm".
ProductList.java
package velocity.calculation;
import java.io.*;
import java.util.*;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
public class ProductList {
public static void main(String args[]) throws Exception {
Velocity.init();
Template template =
Velocity.getTemplate("./src/velocity/calculation/Product.vm");
VelocityContext context = new VelocityContext();
ArrayList list = new ArrayList();
list.add(new Product("Product 1", 111.99));
list.add(new Product("Product 2", 222.89));
list.add(new Product("Product 3", 333.79));
list.add(new Product("Product 4", 444.69));
context.put("productList", list);
Iterator iterator = list.iterator();
Product p = null;
double total = 0.00;
while (iterator.hasNext()) {
p = (Product) iterator.next();
total+=p.getPrice();
}
context.put("totalPrice", new Double(total));
Writer writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer);
}
}
|
Product.java
package velocity.calculation;
public class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
}
|
Product.vm
#foreach($product in $productList)
$product.Name $$product.Price
#end
Total Price: $$totalPrice
|
Output:
Product 1 $111.99
Product 2 $222.89
Product 3 $333.79
Product 4 $444.69
Total Price: $1113.36
|
Download code