1.0          Other languages

2.2 Velocity HTML template


"Velocity is a Java-based template engine." This is official sentence given by Apache. It's not easy to understand for one who has no template relative programming common sense.

Another word, maybe easier to understand, Velocity is a string-replacing Java class library.

For example, Middlegen use Velocity to generate RDBMS relative Java bean files, just need to define the target format template.

Veloicty don't need J2EE server. Which means if we use Velocity to generate dynamic HTML pages, we can run unit test without J2EE server. As our experience, this will make programming faster.

Here is a sample for Velocity to generate dynamic HTML pages:

The above file is pure HTML file, can be edited by web page editor. And here is the Java code:



public class ViewCartDispatcher extends QueryDispatcher {
    public boolean process(HttpServletRequest request, WebAppContext webContext, Controller controller) throws Exception {
        this.setPageTitle("View cart"); HttpSession session = request.getSession();
        Cart cart = (Cart) session.getAttribute(Cart.KEY_IN_SESSION);
        if (cart != null) {
            List cartItemList = cart.getAllCartItems();
            webContext.put("cart_item_list", cartItemList);
        return true;
    }public String getUrlId() {
        return "view_cart";



And this is the runtime result page:


And also, we use Velocity for layout. Which means all pages have the same header, footer, left menu, right notice, etc.