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:
http://velocity.apache.org/download.cgi

Sample Example:


Directory structure:
|-- css
|-- html
|-- images
|-- js
|-- META-INF
|   `-- context.xml
|-- templates
|   `-- Login.vm
`-- WEB-INF
    |-- 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;
   }
}



Login.vm


<HTML>
<head>
<TITLE> Login Page </TITLE>
</head>
<body>
<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>
<tbody>
<tr>
<td> User Name </td>
<td> <input type="text" name="username" id="username"/></td>
</tr>

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


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.

<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>velocity</servlet-name>
<servlet-class>
org.apache.velocity.tools.view.servlet.VelocityViewServlet
</servlet-class>
<init-param>
<param-name>org.apache.velocity.toolbox</param-name>
<param-value>/WEB-INF/toolbox.xml</param-value>
</init-param>
<init-param>
<param-name>org.apache.velocity.properties</param-name>
<param-value>/WEB-INF/velocity.properties</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>velocity</servlet-name>
<url-pattern>*.vm</url-pattern>
</servlet-mapping>
</web-app>


Specifying template path loader: (velocity.properties)

resource.loader = webapp
webapp.resource.loader.class = org.apache.velocity.tools.view.servlet.WebappLoader
webapp.resource.loader.path=templates
webapp.resource.loader.cache = true
runtime.log=WEB-INF/velocity.log
input.encoding=UTF-8
output.encoding=UTF-8


6 comments:

  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..!

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

    ReplyDelete
    Replies
    1. You can find sample xml configuration file from

      http://velocity.apache.org/tools/releases/2.0/config.xml.html

      Delete
  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.

    ReplyDelete