Velocity is a java-based template engine (the role of the template engine is to get the data and process it, and finally display the data).
It allows anyone to simply use the template language to refer to objects defined by Java code.
Mainly used in:
Development of 1.web applications.
2. Generate Sql,xml or code as a template.
3. Used as an integrated component of other systems.
When velocity is applied to application program or a servlet, the main workflows are as follows:
1. Initialize velocity.
2. Create a Context object
3. Add data to Context
4. Select Template
5. Merging templates and data generation output pages
Preparation: Import dependent packages, in the attached below.
Example 1: Application Case
1. template file Hellovelocity.vm file Java code # #这是一行注释, does not output #* This is a multiline comment and does not output multiline comments *#//----------1. Variable assignment output------------Welcome $name to Ja vayou.com! This is $date. Tdday is $mydae.//undefined variable will be string//-----------2. Set variable value, all variables start with $----------------#set ($iAmVariable = "good!") Welcome $name to javayou.com! This is $date. $iAmVariable//-------------3.if,else judgment--------------------------#set ($admin = "admin") #set ($user = "user") #if ($adm in = = $user) Welcome admin! #else Welcome user! #end//--------------4. Iteration Data List---------------------#foreach ($product in $list) $product #end//------------5. Iteration Data hashset-----------------#foreach ($key in $hashVariable. Keyset ()) $key ' s value: $ hashvariable.get ($key) #end//--- --------6. Iteration Data List Bean ($velocityCount is the enumeration number, default starting from 1, adjustable) #foreach ($s in $listBean) < $velocityCount > Address: $ S.address #end//-------------7. Template nesting---------------------#foreach ($element in $list) #foreach ($element in $list) inner : This is ($velocityCount)-$element. #end Outer:this IS ($velocityCount)-$element. #end//-----------8. Import other files, multiple files separated by commas--------------#include ("Com/test2/test.txt")
# #这是一行注释, no output #* This is a multiline comment and does not output multiline comments *#//----------1. Variable assignment output------------Welcome $name to javayou.com!
This is $date.
Tdday is $mydae.//undefined variable will be string//-----------2. Set variable value, all variables start with $----------------#set ($iAmVariable = "good!")
Welcome $name to javayou.com!
This is $date. $iAmVariable//-------------3.if,else judgment--------------------------#set ($admin = "admin") #set ($user = "user") #if ($adm
in = = $user) Welcome admin!
#else Welcome user! #end//--------------4. Iteration Data List---------------------#foreach ($product in $list) $product #end//------------5. Iterative data ha Shset-----------------#foreach ($key in $hashVariable. Keyset ()) $key ' s value: $ hashvariable.get ($key) #end//------- ----6. Iteration Data List Bean ($velocityCount is the enumeration number, default starting from 1, adjustable) #foreach ($s in $listBean) < $velocityCount > Address: $ S.address #end//-------------7. Template nesting---------------------#foreach ($element in $list) #foreach ($element in $list) Inn
Er:this is ($velocityCount)-$element. #end Outer:this is ($velocityCount)-$element. #end//-----------8. Import other files, multiple files separated by commas--------------#include ("Com/test2/test.txt")
2. Other non-template files text.txt Java code ======text.txt==================== This is test ' s Content.yeah.
======text.txt==================== This is
test ' s Content.yeah.
3. Client application test Code: Java code Package com.test2; Import Java.io.FileOutputStream; Import Java.io.StringWriter; Import java.util.*; Import org.apache.velocity.app.Velocity; Import Org.apache.velocity.app.VelocityEngine; Import Org.apache.velocity.Template; Import Org.apache.velocity.VelocityContext; public class Hellovelocity {public static void main (string[] args) throws Exception {//initialization and acquisition of Velocity engine velocityengine ve = new Velocityengine (); Get velocity of the template properties P =new properties (); P.put (Velocity.file_resource_loader_path, "d:/myspace/velocitytest/src"); Ve.init (P); Get velocity of the template Template t = ve.gettemplate ("COM/TEST2/HELLOVELOCITY.VM", "utf-8"); The context of velocity is obtained by velocitycontext contexts = new Velocitycontext (); Filling the data into the context context.put ("name", "Liang"); Context.put ("Date", (new Date ()). ToString ()); For the rear display, enter the list number in advance list temp = new ArrayList (); Temp.add ("Item1"); Temp.add ("item2"); Context.put ("list", temp); List Tempbean = new ArrayList (); Tempbean.add (New UserInfo ("1", "John"," Fujian ")); Tempbean.add (New UserInfo ("2", "Dick", "Hunan")); Context.put ("Listbean", Tempbean); Output stream StringWriter writer = new StringWriter (); Conversion output T.merge (context, writer); Output Information System.out.println (writer.tostring ()); Output to file FileOutputStream of = new FileOutputStream ("D:/velocity.txt"); Of.write (Writer.tostring (). GetBytes ("GBK")); Of.flush (); Of.close (); } }
Package com.test2;
Import Java.io.FileOutputStream;
Import Java.io.StringWriter;
Import java.util.*;
Import org.apache.velocity.app.Velocity;
Import Org.apache.velocity.app.VelocityEngine;
Import Org.apache.velocity.Template;
Import Org.apache.velocity.VelocityContext; public class Hellovelocity {public static void main (string[] args) throws Exception {//Initialize and obtain velocity engine velocity
Engine ve = new Velocityengine ();
Get velocity of the template properties P =new properties ();
P.put (Velocity.file_resource_loader_path, "d:/myspace/velocitytest/src");
Ve.init (P);
Get velocity of the template Template t = ve.gettemplate ("COM/TEST2/HELLOVELOCITY.VM", "utf-8");
The context of velocity is obtained by velocitycontext contexts = new Velocitycontext ();
Filling the data into the context context.put ("name", "Liang");
Context.put ("Date", (new Date ()). ToString ());
For the rear display, enter the list number in advance list temp = new ArrayList ();
Temp.add ("Item1");
Temp.add ("item2");
Context.put ("list", temp); List Tempbean = new ArrayList ();
Tempbean.add (New UserInfo ("1", "John", "Fujian"));
Tempbean.add (New UserInfo ("2", "Dick", "Hunan"));
Context.put ("Listbean", Tempbean);
Output stream StringWriter writer = new StringWriter ();
Conversion output T.merge (context, writer);
Output Information System.out.println (writer.tostring ());
Output to file FileOutputStream of = new FileOutputStream ("D:/velocity.txt");
Of.write (Writer.tostring (). GetBytes ("GBK"));
Of.flush ();
Of.close ();
}
}
4.UserInfo entity class Java code package COM.TEST2; public class UserInfo {private string userId, private string userName, private string address, public UserInfo (String use RId, String userName, string address) {super (); this.userid = userId; this.username = userName; this.address = Address;} public string GetUserID () {return userId.} public void Setuserid (String userId) {this.userid = userId;} public string GetUserName () {return userName.} public void Setusername (String userName) {this.username = userName;} public String G Etaddress () {return address;} public void setaddress (String address) {this.address = address;}
Package com.test2;
public class UserInfo {
private String userId;
Private String userName;
Private String address;
Public UserInfo (String userId, String userName, string address) {
super ();
This.userid = userId;
This.username = UserName;
this.address = address;
Public String GetUserID () {return
userId;
}
public void Setuserid (String userId) {
This.userid = userId;
}
Public String GetUserName () {return
userName;
}
public void Setusername (String userName) {
this.username = userName;
}
Public String getaddress () {return address
;
}
public void setaddress (String address) {
this.address = address;
}
}
Example 2:web application case
1. Establish a velocity directory under the Web-inf directory and create a template file VELOCITY.VM. Java code
2. Create velocity.properties properties file in Web-inf directory java code resource.loader = File File.resource.loader.path =/web-inf/velocity File.resource.loader.cache = True File.resource.loader.modificationCheckInterval = 300
Resource.loader = File
File.resource.loader.path =/web-inf/velocity
File.resource.loader.cache = True
File.resource.loader.modificationCheckInterval = 300
3. Set up servlet file Velocityservlettest.java Java code package servlet; Import java.io.IOException; Import Java.io.StringWriter; Import java.util.ArrayList; Import java.util.List; Import Javax.servlet.ServletConfig; Import Javax.servlet.http.HttpServletRequest; Import Javax.servlet.http.HttpServletResponse; Import org.apache.commons.collections.ExtendedProperties; Import Org.apache.velocity.Template; Import org.apache.velocity.app.Velocity; Import Org.apache.velocity.context.Context; Import Org.apache.velocity.tools.view.servlet.VelocityViewServlet; Import Com.test2.UserInfo; public class Velocityservlettest extends velocityviewservlet{private static final long serialversionuid = 1L;//First step loading configuration text This method is invoked in the Velocityservlet initialization method init () protected extendedproperties loadconfiguration (servletconfig config) throws IOException {extendedproperties p = super.loadconfiguration (config);//Get the Velocity template path String configured in Velocity.properties Velocityloadpath = p.getstring (Velocity.file_resource_loader_path); if (Velocityloadpath!= null) {//Get the absolute path of the template path Velocityloadpath = Getservletcontext (). Getrealpath (Velocityloadpath); if ( Velocityloadpath!= null) {//Reset template path System.out.println ("VMPath2:" +velocityloadpath); P.setproperty (Velocity.file_resource_loader_path, Velocityloadpath); } return p; } protected Template HandleRequest (httpservletrequest req, httpservletresponse res, context) throws exception{// Character encoding req.setcharacterencoding ("gb2312"); Res.setcharacterencoding ("gb2312"); Page Output Res.setcontenttype ("text/html;charset=" + "gb2312"); List Tempbean = new ArrayList (); Tempbean.add (New UserInfo ("1", "John", "Fujian")); Tempbean.add (New UserInfo ("2", "Dick", "Hunan")); Context.put ("Listbean", Tempbean); String templatename = "VELOCITY.VM"; Test information output Template t= gettemplate (templatename, "utf-8"); StringWriter writer = new StringWriter (); Conversion output T.merge (context, writer); Output Information System.out.println (writer.tostring ()); Get Template page show return templatename!= null? GetTemplate (templatename, "Utf-8"): nulL } }
Package servlet;
Import java.io.IOException;
Import Java.io.StringWriter;
Import java.util.ArrayList;
Import java.util.List;
Import Javax.servlet.ServletConfig;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import org.apache.commons.collections.ExtendedProperties;
Import Org.apache.velocity.Template;
Import org.apache.velocity.app.Velocity;
Import Org.apache.velocity.context.Context;
Import Org.apache.velocity.tools.view.servlet.VelocityViewServlet;
Import Com.test2.UserInfo;
public class Velocityservlettest extends velocityviewservlet{private static final long serialversionuid = 1L; The first step is to load the configuration file This method is invoked in the Velocityservlet initialization method init () protected extendedproperties loadconfiguration (servletconfig
Config) throws IOException {extendedproperties p = super.loadconfiguration (config); Gets the Velocity template path configured in velocity.properties String Velocityloadpath = p.getstring (Velocity.file_resource_loader_path) ;
if (Velocityloadpath!= null) {//Get the absolute path of the template path Velocityloadpath = Getservletcont
Ext (). Getrealpath (Velocityloadpath);
if (Velocityloadpath!= null) {//Reset template path System.out.println ("VMPath2:" +velocityloadpath);
P.setproperty (Velocity.file_resource_loader_path, Velocityloadpath);
} return p; Protected Template HandleRequest (httpservletrequest req, httpservletresponse res, context Contex
T) throws exception{//character encoding req.setcharacterencoding ("gb2312");
Res.setcharacterencoding ("gb2312");
Page Output Res.setcontenttype ("text/html;charset=" + "gb2312");
List Tempbean = new ArrayList ();
Tempbean.add (New UserInfo ("1", "John", "Fujian"));
Tempbean.add (New UserInfo ("2", "Dick", "Hunan"));
Context.put ("Listbean", Tempbean);
String templatename = "VELOCITY.VM"; Test information Output TemPlate t= gettemplate (templatename, "utf-8");
StringWriter writer = new StringWriter ();
Conversion output T.merge (context, writer);
Output Information System.out.println (writer.tostring ()); Get Template page show return templatename!= null?
GetTemplate (templatename, "Utf-8"): null;
}
}
4. Configure the XML code in the Web.xml file <?xml version= "1.0" encoding= "UTF-8"?> <web-app version= "2.4" xmlns= "http://" Java.sun.com/xml/ns/j2ee "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http:// JAVA.SUN.COM/XML/NS/J2EE http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd "> <servlet> <servlet-name >velocityServletTest</servlet-name> <