What is Velocity?

Velocity is a Java-based template engine. It permits web page designers to reference methods defined in Java code.

What is Velocity?

What is Velocity?

     

Velocity is a Java-based template engine. It permits web page designers to reference methods defined in Java code. At the Jakarta Velocity Project Website, where you can download the freely available source code, a thriving and growing community of users is ready to answer questions and offer solutions to common templating problems. Jakarta Velocity Project Website, offers the freely available code, and also provide a technical support community that how to use that code.

Why should I use it?

Velocity provides functionality to designed and use general templating tools, so that it can work with any Java application that requires data formatting and presentation as well.
 
Some reasons to use velocity :

  • It adapts to many application areas
  • It provides a simple and clear syntax for the template designer
  • It offers a simple programming model for the developer
  • With velocity you can develop and maintain template  and code separately.
  • The Velocity engine provides easy integration with any Java application environment.
  • Velocity enables templates to access any public method of data objects in the context

Velocity Template Language (VTL):

The Velocity Template Language (VTL) provides the easiest and simplest way to show and process dynamic content in web page. Velocity use references to add dynamic content in web page, variables are one type of reference that can use as a reference to refer something in java code, or it can get its value from a VTL statement. 
Here is an example of a VTL statement that can be  embedded in an HTML document:

#set( $name = "Komal" )

This VTL statement begins with the # character and contains a directive: set. When a client requests your web page, the Velocity Templating Engine will search through your web page to find all # characters, then determine which mark the beginning of VTL statements, and which of the # characters that have nothing to do with VTL.

The # character is followed by a directive, set. The set directive used an expression (enclosed in brackets) - an equation that assigns a value to a variable. The variable is list on the left hand side and its value on the right hand side, these two are separated by an = character.

References

There are three types of references in the VTL: variables, properties and methods. As a programers using the VTL, The engineers must have an agreement on the references so you can use them correctly in your templates for proper functionality.

Variables

Velocity uses variable declaration with '$' sign.

Rules to declare variables:
A VTL Identifier must start with an alphabetic character (a .. z or A .. Z). The rest of the characters are limited to the following types of characters:

  • alphabetic (a .. z, A .. Z)
  • numeric (0 .. 9)
  • hyphen ("-")
  • underscore ("_")

Here are some examples of valid variable references in the VTL:

    $name

    $firstName

    $first-name

    $first_name

    $firstName1

When VTL references a variable, such as $name, the variable can gets its value from either a set directive in the template, or from the Java code. For example, if the Java variable $name has the value bar at the time the template is requested, bar replaces all instances of $name on the web page. Alternatively, if I include the statement

    #set( $name = "Komal" )

The output will be the same for all instances of $name that follow this directive.

Properties

Second reference of VTL is properties, and properties have a different format. To create properties in velocity uses '$' character followed a VTL Identifier, followed by a dot character (".") and another VTL Identifier and so on. 
These are some examples of valid property references in the VTL:

    $customer.Address

    $purchase.Total

Methods

A method is use to do some task and defined in java code. Methods are references that consists of a leading "$" character followed a VTL Identifier. These are examples of valid method references in the VTL:

    $customer.getAddress()

    $purchase.getTotal()

    $page.setTitle( "Home Page" ) 0

    $person.setAttributes( ["Name", "Age", "Gender"] )

This notation is used for the following Methods

    $person.getName() 1

    $person.getAge()

    $person.getGender()

We might expect these methods to return the names of person from variable 'person' : 2

    $person.getName( ["Ajay", "Komal", "Santosh"] )
    ## Can't pass a parameter list with $person.getName

    $book.setTitle( "Java Programing" )
    ## Can't pass a parameter list

Conditionals 3

If / ElseIf / Else

The #if directive in Velocity allows for text to be included when the web page is generated, on the conditional that the if statement is true. For example:

    #if( $flag ) 4

      <strong>Suman </strong>

    #end

An #elseif or #else element can be used with an #if element. 5

    #if( $flag == 1 )
      komal
    #elseif( $flag == 2 )
      Santosh
    #elseif( $flag == 3 )
      Ajay
    #else
      Rakesh
    #end

Logical AND operators

    ## logical AND 6

    #if( $flag && $flag1 )
      komal
    #end

Logical OR operators

    ## logical OR 7

    #if( $flag || $flag1 )
      komal
    #end

Logical NOT operators

    ## logical NOT 8

    #if( !$flag )
      komal
    #end

Loops

Foreach Loop 9

The #foreach element allows for looping. For example:

    First example:
    #foreach( $i in [1..5] )
    $i
    #end

    Second example:
    #foreach( $bar in [2..-2] )
    $bar
    #end
    0

    Third example:
    #set( $arr = [0..1] )
    #foreach( $i in $arr )
    $i
    #end

Produces the following output:

    First example:
    1 2 3 4 5
    1

    Second example:
    2 1 0 -1 -2

    Third example:
    0 1

Example 2

Stu.vm


    No of student is : $stuDetails.size()

    Details of student

    #foreach( $stu in $stuDetails )
    Roll No - $stu.rno
    Name - $stu.name
    Class - $stu.cla

    #end
    ------------------------

Stu.java


    import java.io.StringWriter;
    import java.util.*;
    import org.apache.velocity.Template;
    import org.apache.velocity.VelocityContext;
    import org.apache.velocity.app.VelocityEngine;

    public class Stu {

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

      VelocityEngine ve = new VelocityEngine();
      ve.init();

      ArrayList list = new ArrayList();

      Map map = new HashMap();
      map.put("rno""1");
      map.put("name""Komal");
      map.put("cla""Bca");
      list.add(map);

      map = new HashMap();
      map.put("rno""2");
      map.put("name""Komal");
      map.put("cla""Bca");
      list.add(map);

      VelocityContext context = new VelocityContext();
      context.put("stuDetails", list);
      context.put("Name"new Stu());

      Template t = ve.getTemplate("stu.vm");
      StringWriter writer = new StringWriter();
      t.merge(context, writer);

      System.out.println(writer);
      }
    }

Output 3

    No of student is : 2

    Details of student

    Roll No - 1
    Name  - Komal
    Class - Bca

    Roll No - 2
    Name  - Komal
    Class - Bca

    -------

Download code: