Basic syntax Velocity entry

Recommended for you: Get network issues from WhatsUp Gold. Not end users.
1.     Variables
(1)Variable definitions:
#set($name = "hello")      Description: velocity is a weak type variables.
When using the #set command, a literal string enclosed in double quotes will parse and re interpretation, as shown below:
#set($directoryRoot = "www" )
#set($templateName = "index.vm" )
#set($template = "$directoryRoot/$templateName" )
The output will be: www/index.vm
Note: the use of .5 in velocity of such currency identifier is no problem, because the variables in velocity always begin with an uppercase or lowercase letters.
(2)Variable specification method
${name} , Can also be written as: $name. Promote the use of the method.
For example: you want to organize a string through a variable $vice.
Jack is a $vicemaniac.
Originally the variable is $vice but it has now become $vicemaniac, so Veloctiy don't know what you really want. So, should use the writing standard format : Jack is a ${vice}maniac
Now Velocity know variable is $vice rather than$vicemaniac.
Note: when you can't add attribute references{}
(3)Variable assignment:
The left side of the assignment must be a variable or attribute reference. The right may be one of the following six types:
Variable references, a literal string, attribute references, reference, literal numbers, array list.
The following example demonstrates each type of the above:
#set( $monkey = $bill ) ## variable reference
#set( $monkey.Friend = "monica" ) ## string
#set( $monkey.Blame = $whitehouse.Leak ) ## property reference
#set( $monkey.Plan = $spindoctor.weave($web) ) ## method reference
#set( $monkey.Number = 123 ) ##number
#set( $monkey.Say = ["Not", $my, "fault"] ) ## ArrayList
Note: if the above example rvalue is null, is an lvalue is not assigned, that will keep the previous value.
The velocity template is not defined variables will be considered as a string. For example:
#set($foo = "gibbous")
$moon = $foo
Output results:
$moon = gibbous
Not the velocity template interpret reference as an instance of an object variable. For example: $foo.Name will be interpreted as a Foo object's getName () method, instead of the Foo object's Name instance variables. For example:
$foo.getBar() Equal to$foo.Bar ,
$data.getUser("jon") Equal to$data.User("jon") ,
data.getRequest().getServerName() Equal to
$Data.Request.ServerName is equivalent to${data.Request.ServerName}

2.     Cycle
#foreach ($element in $list)
     This is $element.
#set( $list = ["pine", "oak", "maple"])
#foreach ($element in $list)
This is $element.<br>
The output results:
1 This is pine.
2 This is oak.
3 This is maple.
A value of each loop in $list will be assigned to the $element variable.
$List can be a Vector, Hashtable or Array. Assigned to the value of $element is a Java object, and can be referenced by the variable. For example: if the $element t is a Java Product class, and the name of the product can be done by calling his getName () method.
#foreach ( $key in $list.keySet())
Key: $key -> Value: $list.get($key) <br>
Tip: velocity is case sensitive.
Velocity also provides methods to obtain cycles, the $velocityCount variable is the name of the default Velocity name.

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

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

  Third example:
  #set ( $arr = [0..1] )
  #foreach ( $i in $arr )
The output above three examples of results:
  First example:
  1 2 3 4 5

  Second example:
  2 1 0 -1 -2

  Third example:
  0 1

3.     Conditional statements
#if (condition)
#elseif (condition)
4.     Nesting
    #foreach ($element in $list)
       ## Inner foreach cycle
       #foreach ($element in $list)
       This is $element. $velocityCount <br>inner<br>
       ## Inner foreach in the loop end
    ## outer foreach
    This is $element.
    $velocityCount <br>outer<br>
The statement can be nested in other, such as #if... #else... #end.
5.      Notes
(1)Single line comment:
  ## This is a single line comment.
(2)Multi line comments:
   Thus begins a multi-line comment. Online visitors won't
   see this text because the Velocity Templating Engine will
  ignore it.
(3)Document format:
   This is a VTL comment block and
   may be used to store such information
  as the document author and versioning
   @version 1.1
   @author  xiao
6.     Relational and logical operators
Velocity also has the logic AND, OR and NOT operator.
Such as
## example for AND
#if($foo && $bar)
   <strong> This AND that</strong>
In the example the #if () instruction only in $foo and $bar bucket is true when it is true. If $foo is false, the expression is false; and $bar will not be evaluated. If $foo is true, Velocity template engine will continue to examine the value of $bar, if $bar is true, then the entire expression is true. And the output of This AND that. If $bar is false, there will be no output because the expression is false.
The macros in 7.Velocity
The macros in Velocity we can understand the function.
The macro definition
#Macro (the name $ parameters, 2 parameters of macro …)
Statement body (namely the function body)
The macro call
#Macro name ( parameter parameter …)
    Note: parameters are separated by spaces.
Stop execution and returns the template engine, apply it to the debug is very helpful.
9.#Include and#parse
#Include and #parse are introduced into the local file, for reasons of safety, be introduced only local file in the TEMPLATE_ROOT directory.
(1) Unlike #include, #parse can specify only a single object. While #include may have more than one
If you need to introduce multiple files, can be separated on the line with a comma:
#include ("one.gif", "two.txt", "three.htm" )
In the brackets can be a file name, but more time is to use the variable:
#include ( "greetings.txt", $seasonalstock )
(2)#Include was introduced to the contents of the file will not be parsed by the template engine,
#parse introduced the contents of the file Velocity will parse the velocity syntax and handed over to the template, meaning that fairly and to introduce copy file to file.
#Parse is a recursive calls, for example: if the dofoo.vm contains such as down:
Count down.<br>
#set ($count =
#parse ("parsefoo.vm")
<br>All done with dofoo.vm!
So in the parsefoo.vm template, you can include the following VTL:
#set($count = $count - 1)
#if ( $count > 0 )<br>
#parse( "parsefoo.vm" )
<br>All done with parsefoo.vm!
#End display results:
Count down.
All done with parsefoo.vm!
All done with dofoo.vm!
Note: use #parse to nest another VM variable sharing problem in vm. Such as:
->The a.vm nested b.vm,
->A.vm in the definition of the variables $param,
->Can directly use the $param b.vm, without any restrictions.
But the need to pay particular attention to is, if b.vm also defines a variable $param, then b.vm will use the value defined in the b.vm.
10.The use of escape character'\'.
If reference is defined, two '\' means that the output of a '\', if not defined, just as output. Such as:
#set($email = "foo" )
If $email is not defined

11.The built-in objects
The built-in Velocity objects, you can call directly in the VM template, listed as follows.:
$request, $response, $session, In addition, the use of information tools to access Struts in $msg can also be the template of the international resources, to achieve simple internationalization.
The 12 array access
The problems in the Velocity array accesses, Because Velocity can only access objects, While the array is a special Array, So although the array can be circulated lists, But it cannot locate the access location specific element, Such as STRs[2], Array access to fixed position elements called reflection method of Array get(Object array, int index), While the Velocity does not provide such access, So arrays or into other List containers way of packing, Either provided by public class Util way, Afferent array object to access the location parameter, In order to achieve the desired value to return.

Sample parts
1.Hello world sample code:
(1)The Velocity template(hello.html)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<TITLE> New Document </TITLE>
    hello,$name!                 (Note: the name name and in here to be consistent)
(2)The velocity template content conversion category(
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;

* Velocity conversion
* @author
public class VelocityTest
     * The main function
     * @param args
    public static void main(String[] args)
      //Access the template engine
        VelocityEngine ve = new VelocityEngine();
        //Path to the template files are located
        String path = "D:/java/jproject/regedit/webroot";     
        //Set parameters
        ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
//Treatment Chinese problem
            //Initialize template
            //Obtaining template(hello.html)

The name Velocity template
            Template template = ve.getTemplate("hello.html");  
            //Access to context
            VelocityContext root = new VelocityContext();
            //The data in the context of
            root.put("name","world");                     (Note: the above the corresponding)
//The output path
            Strint outpath = "e:/helloworld.html";
            Writer mywriter = new PrintWriter(new FileOutputStream(
                new File(outpath)));          
            template.merge(root, mywriter);
        catch (Exception e)
(3)Environment to build
In the Lib directory are copy: velocity-1.4.jar, velocity-dept.jar;
Download address:
(4)After the operation result are as follows:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<TITLE> New Document </TITLE>

2.Servlet and Velocity combined with example
  <body bgcolor="#ffffff">
    <h2>Welcom to Velocity!</h2>
    <i>Here's the list of people</i>
    <table cellspacing="0" cellpadding="5" width="20%" >
    <td bgcolor="#eeeeee" align="center">
    #foreach ($name in $theList)
    <td bgcolor="#eeeeee" align="center">$name</td>
package com.koal.velocity;

import java.util.ArrayList;
import java.util.Properties;
import java.util.Vector;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.servlet.VelocityServlet;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;

public class SampleServlet extends VelocityServlet
     * By the VelocityServlet.init (calling),
     * This finding template path
    protected Properties loadConfiguration(ServletConfig config )
        throws IOException, FileNotFoundException {
        Properties p = new Properties();
        //Access path
        String path = config.getServletContext().getRealPath("/");
        if (path == null)
            System.out.println(" SampleServlet.loadConfiguration() : unable to "
                    + "get the current webapp root.  Using '/'. Please fix.");
            path = "/";
        //Set path
        p.setProperty( Velocity.FILE_RESOURCE_LOADER_PATH, path);
        return p;

     * The business logic processing method in Velocity major, VelocityServlet automatically by the call
     * @Param CTX template context           
     * @Return Template template information
    public Template handleRequest( HttpServletRequest request,
       HttpServletResponse response, Context ctx )
        //The main set up the demonstration data, business process development in this call the corresponding,

        //And set to return to the page data
        //The list of data to be displayed
        String p1 = "The first: LiuDong";
        String p2 = "Second: Liang.xf";
        Vector personList = new Vector();
        //Chinese need to convert
        try {
            personList.addElement(new String(p1.getBytes(), "ISO-8859-1") );
            personList.addElement(new String(p2.getBytes(), "ISO-8859-1") );
        } catch (Exception e) {
            System.out.println("Data conversion anomaly: "+e);   
        //Setting data for a page template, replace the display data
        ctx.put("theList", personList );  
        //Definition template      
        Template outty = null;      
            //The template
            outty =  getTemplate("example.html");          
        catch( ParseErrorException pee )
            System.out.println("SampleServlet: parse error for template " + pee);
        catch( ResourceNotFoundException rnfe )
            System.out.println("SampleServlet: template not found " + rnfe);
        catch( Exception e )
            System.out.println("Error " + e);
        return outty;

(3)In the web.xml configuration:

(4)Environment to build
In the Lib directory are copy: commons-collections.jar,velocity-1.4.jar, velocity-dept.jar;
    Tomcat normal operating environment.
    Start Tomcat, input in the IE: http://localhost:8080/example, page display data list:
Here's the list of people
The first: LiuDong
Second: Liang.xf
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Amber at December 05, 2013 - 6:55 AM