06 March 2011

Using Apache Velocity for MVC : Sample Login example

Velocity is a Java-based template engine. It permits anyone to use a simple yet powerful template language to reference objects defined in Java code. When Velocity is used for web development, Web designers can work in parallel with Java programmers to develop web sites according to the Model-View-Controller (MVC) model, meaning that web page designers can focus solely on creating a site that looks good, and programmers can focus solely on writing top-notch code. Velocity separates Java code from the web pages, making the web site more maintainable over its lifespan and providing a viable alternative to JSP or PHP.

Velocity can be used to generate web pages, SQL, PostScript and other output from templates. It can be used either as a standalone utility for generating source code and reports, or as an integrated component of other systems. When complete, Velocity will provide template services for the Turbin web application framework. Velocity+Turbine will provide a template service that will allow web applications to be developed according to a true MVC model.

Dowload Apache tools and engine from:

Sample Example:

Directory structure:
|-- css
|-- html
|-- images
|-- js
|   `-- context.xml
|-- templates
|   `-- Login.vm
    |-- classes
    |   `-com
    |   |  `-- Login.class
    |   `-- log4j.properties
    |-- lib
    |   |-- antlr-2.7.5.jar
    |   |-- avalon-logkit-2.1.jar
    |   |-- Base64.jar
    |   |-- commons-beanutils-1.7.0.jar
    |   |-- commons-chain-1.1.jar
    |   |-- commons-collections-3.2.1.jar
    |   |-- commons-collections-3.2.jar
    |   |-- commons-dbcp-1.2.2.jar
    |   |-- commons-digester-1.8.jar
    |   |-- commons-lang-2.2.jar
    |   |-- commons-lang-2.4.jar
    |   |-- commons-logging-1.1.jar
    |   |-- commons-validator-1.3.1.jar
    |   |-- jdom-1.0.jar
    |   |-- log4j-1.2.12.jar
    |   |-- oro-2.0.8.jar
    |   |-- velocity-1.7.jar
    |   |-- velocity-tools-2.0.jar
    |   |-- velocity-tools-generic-2.0.jar
    |   |-- velocity-tools-view-2.0.jar
    |   `-- werken-xpath-0.9.4.jar
    |-- velocity.properties
    `-- web.xml

Login servlet: (Login.java)

import java.io.*;
import java.util.Date;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;

import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.servlet.VelocityServlet;
import org.apache.velocity.tools.view.VelocityViewServlet;

public class Login extends VelocityViewServlet
   public Template handleRequest( HttpServletRequest request,
      HttpServletResponse response, Context context )
   /* get the template */
   Template template = null;
      context.put("application", "Test Application");
      // context.put("header", "Velocity Sample Page");
      try {
         template = getTemplate("login.vm"); 
      } catch(Exception e ) {
         System.out.println("Error " + e);
      return template;


<TITLE> Login Page </TITLE>
<H3> $application </h3>
<form name="loginform" id="loginform" action="/vtest/Login" method="post">
<table width="34%" align="center" cellspacing=3 class="window" border="1" cellpadding=5>
<td> User Name </td>
<td> <input type="text" name="username" id="username"/></td>

<tr><td colspan="2" class="errortext"><span name="error_password" id="error_password"></span></td></tr>
<td> Password </td>
<td> <input type="password" name="password" id="password"/></td>
<td colspan="3" align="center">
<input type="submit" value="Login"/>

VelocityView includes all of the GenricTools and adds infrastructure and specialized tools for using Velocity in the view layer of web applications (Java EE projects). This includes the VelocityViewServlet or VelocityLayoutServlet for processing Velocity template requests and the VelocityViewTag for embedding Velocity in JSP.
Key features:
  • VelocityViewServlet: standalone servlet that renders Velocity templates. Invoked directly from web clients requests, or via servlet forwarding similar to how JSP files are rendered by JSPServlet.
  • The HttpServletRequest, HttpSession, ServletContext, and their attributes are automatically available in your templates.
  • Tools can also be made available to your templates, through a tools  configuration file.
  • A number of useful, extendable tools for developing web applications are already provided for your convenience.
  • Logging can be directed to the log infrastructure of the Web application. (default is the logging facility provided by the Servlet API).
Servlet Setup (web.xml):

The servlet configuration (web.xml) must be modified to include a reference to the VelocityViewServlet (or subclass thereof) which will perform the rendering. All *.vm files are mapped to this servlet which will populate the 'context' with Request, Session, and Application scopes plus any additional tools specified by your configuration (or provided as defaults). The servlet will use this contextual information and the Velocity Engine to render the template file.



Specifying template path loader: (velocity.properties)

resource.loader = webapp
webapp.resource.loader.class = org.apache.velocity.tools.view.servlet.WebappLoader
webapp.resource.loader.cache = true


  1. This is a nice article..
    Its very easy to understand ..
    And this article is using to learn something about it..
    c#, dot.net, php tutorial
    Thanks a lot..!

  2. Where is toolbox.xml file. What are its contents?

    1. You can find sample xml configuration file from


  3. Good tutorial. What if i don't want to render output to browser. Let's say if i have to print to console only.