1. 程式人生 > >基於java的Velocity模板匹配引擎

基於java的Velocity模板匹配引擎

Velocity是一個基於java的模板引擎(模板引擎的作用就是取得資料並加以處理,最後顯示出資料)。
它允許任何人僅僅簡單的使用模板語言來引用由java程式碼定義的物件。

主要應用在:
 1.Web應用的開發。
 2.作為模板產生SQL,XML或程式碼等。
 3.作為其他系統的整合元件使用。

當Velocity應用於application program或 a servlet,主要工作流程如下:
 1.初始化Velocity.
 2.建立Context物件
 3.新增資料到Context
 4.選擇模板
 5.合併模板和資料產生輸出頁面

準備工作:匯入相關依賴包,在下面附件中。

例1:應用程式事例

1.模板檔案hellovelocity.vm檔案

Java程式碼 複製程式碼 收藏程式碼
  1. ##這是一行註釋,不會輸出
  2. #*這是多行註釋,不會輸出
  3. 多行註釋*#
  4. // ---------- 1.變數賦值輸出------------
  5. Welcome $name to Javayou.com!
  6. today is $date.
  7. tdday is $mydae.//未被定義的變數將當成字串
  8. // -----------2.設定變數值,所有變數都以$開頭----------------
  9. #set( $iAmVariable = "good!" )
  10. Welcome $name to Javayou.com!
  11. today is $date.
  12. $iAmVariable
  13. //-------------3.if,else判斷--------------------------
  14. #set ($admin = "admin")
  15. #set ($user = "user")
  16. #if ($admin == $user)
  17. Welcome admin!
  18. #else
  19. Welcome user!
  20. #end
  21. //--------------4.迭代資料List---------------------
  22. #foreach( $product in $list )
  23. $product
  24. #end
  25. // ------------5.迭代資料HashSet-----------------
  26. #foreach($key in $hashVariable.keySet() )
  27. $key ‘s value: $ hashVariable.get($key)
  28. #end
  29. //-----------6.迭代資料List Bean($velocityCount為列舉序號,預設從1開始,可調整)
  30. #foreach ($s in $listBean)
  31. <$velocityCount> Address: $s.address
  32. #end
  33. //-------------7.模板巢狀---------------------
  34. #foreach ($element in $list)
  35. #foreach ($element in $list)
  36. inner:This is ($velocityCount)- $element.
  37. #end
  38. outer:This is ($velocityCount)- $element.
  39. #end
  40. //-----------8.匯入其它檔案,多個檔案用逗號隔開--------------
  41. #include("com/test2/test.txt")
##這是一行註釋,不會輸出
#*這是多行註釋,不會輸出
   多行註釋*#
// ---------- 1.變數賦值輸出------------
Welcome $name to Javayou.com!
today is $date.
tdday is $mydae.//未被定義的變數將當成字串

// -----------2.設定變數值,所有變數都以$開頭----------------
#set( $iAmVariable = "good!" )
Welcome $name to Javayou.com!
today is $date.
$iAmVariable

//-------------3.if,else判斷--------------------------
#set ($admin = "admin")
#set ($user = "user")
#if ($admin == $user)
Welcome admin!
#else
Welcome user!
#end

//--------------4.迭代資料List---------------------
#foreach( $product in $list )
$product
#end

// ------------5.迭代資料HashSet-----------------
#foreach($key in $hashVariable.keySet() )  
$key ‘s value: $ hashVariable.get($key)
#end

//-----------6.迭代資料List Bean($velocityCount為列舉序號,預設從1開始,可調整)
#foreach ($s in $listBean)
<$velocityCount> Address: $s.address
#end

//-------------7.模板巢狀---------------------
#foreach ($element in $list)
	#foreach ($element in $list)
	inner:This is ($velocityCount)- $element.
	#end
outer:This is ($velocityCount)- $element.
#end

//-----------8.匯入其它檔案,多個檔案用逗號隔開--------------
#include("com/test2/test.txt")

2.其它非模板檔案text.txt

Java程式碼 複製程式碼 收藏程式碼
  1. ======text.txt====================
  2. this is test's content.yeah.
   ======text.txt====================
   this is test's content.yeah.

3.客戶端應用測試程式碼:

Java程式碼 複製程式碼 收藏程式碼
  1. package com.test2;
  2. import java.io.FileOutputStream;
  3. import java.io.StringWriter;
  4. import java.util.*;
  5. import org.apache.velocity.app.Velocity;
  6. import org.apache.velocity.app.VelocityEngine;
  7. import org.apache.velocity.Template;
  8. import org.apache.velocity.VelocityContext;
  9. public class HelloVelocity {
  10. public static void main(String[] args) throws Exception {
  11. // 初始化並取得Velocity引擎
  12. VelocityEngine ve = new VelocityEngine();
  13. // 取得velocity的模版
  14. Properties p =new Properties();
  15. p.put(Velocity.FILE_RESOURCE_LOADER_PATH, "D:/myspace/VelocityTest/src");
  16. ve.init(p);
  17. //取得velocity的模版
  18. Template t = ve.getTemplate("com/test2/hellovelocity.vm","utf-8");
  19. // 取得velocity的上下文context
  20. VelocityContext context = new VelocityContext();
  21. // 把資料填入上下文
  22. context.put("name", "Liang");
  23. context.put("date", (new Date()).toString());
  24. // 為後面的展示,提前輸入List數值
  25. List temp = new ArrayList();
  26. temp.add("item1");
  27. temp.add("item2");
  28. context.put("list", temp);
  29. List tempBean = new ArrayList();
  30. tempBean.add(new UserInfo("1","張三","福建"));
  31. tempBean.add(new UserInfo("2","李四","湖南"));
  32. context.put("listBean", tempBean);
  33. // 輸出流
  34. StringWriter writer = new StringWriter();
  35. // 轉換輸出
  36. t.merge(context, writer);
  37. // 輸出資訊
  38. System.out.println(writer.toString());
  39. // 輸出到檔案
  40. FileOutputStream of = new FileOutputStream("d:/velocity.txt");
  41. of.write(writer.toString().getBytes("GBK"));
  42. of.flush();
  43. of.close();
  44. }
  45. }
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 {

		// 初始化並取得Velocity引擎
		VelocityEngine ve = new VelocityEngine();

		// 取得velocity的模版		
		Properties p =new Properties();
		p.put(Velocity.FILE_RESOURCE_LOADER_PATH, "D:/myspace/VelocityTest/src");
		ve.init(p);
		
		//取得velocity的模版 
		Template t = ve.getTemplate("com/test2/hellovelocity.vm","utf-8"); 	

		// 取得velocity的上下文context
		VelocityContext context = new VelocityContext();

		// 把資料填入上下文
		context.put("name", "Liang");
		context.put("date", (new Date()).toString());

		// 為後面的展示,提前輸入List數值
		List temp = new ArrayList();
		temp.add("item1");
		temp.add("item2");
		context.put("list", temp);		
		List tempBean = new ArrayList();
		tempBean.add(new UserInfo("1","張三","福建"));
		tempBean.add(new UserInfo("2","李四","湖南"));
		context.put("listBean", tempBean);

		// 輸出流
		StringWriter writer = new StringWriter();
		// 轉換輸出
		t.merge(context, writer);
		// 輸出資訊
		System.out.println(writer.toString());
		
		// 輸出到檔案
		FileOutputStream of = new FileOutputStream("d:/velocity.txt");
                           of.write(writer.toString().getBytes("GBK")); 
                           of.flush();
                           of.close();		
	}
}

4.UserInfo實體類

Java程式碼 複製程式碼 收藏程式碼
  1. package com.test2;
  2. public class UserInfo {
  3. private String userId;
  4. private String userName;
  5. private String address;
  6. public UserInfo(String userId, String userName, String address) {
  7. super();
  8. this.userId = userId;
  9. this.userName = userName;
  10. this.address = address;
  11. }
  12. public String getUserId() {
  13. return userId;
  14. }
  15. public void setUserId(String userId) {
  16. this.userId = userId;
  17. }
  18. public String getUserName() {
  19. return userName;
  20. }
  21. public void setUserName(String userName) {
  22. this.userName = userName;
  23. }
  24. public String getAddress() {
  25. return address;
  26. }
  27. public void setAddress(String address) {
  28. this.address = address;
  29. }
  30. }
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;
	}
}

例2:Web應用事例

1.在web-inf目錄下建立velocity目錄,建立一模板檔案velocity.vm。

Java程式碼 複製程式碼 收藏程式碼
  1. <html>
  2. <title>hello!Lizhiwo_wo!</title>
  3. <body>
  4. #set($foo = "Velocity")
  5. Hello $foo World! 歡迎您~~~~~~~~~~~~
  6. <table>
  7. <tr>
  8. <td>ID</td><td>姓名</td><td>地址</td>
  9. </tr>
  10. #foreach ($s in $listBean)
  11. <tr>
  12. <td>$s.userId</td><td>$s.userName</td><td>$s.address</td>
  13. </tr>
  14. #end
  15. </table>
  16. </body>
  17. </html>
<html>
<title>hello!Lizhiwo_wo!</title>
<body>
#set($foo = "Velocity")
Hello $foo World!  歡迎您~~~~~~~~~~~~
<table>
	<tr>
		<td>ID</td><td>姓名</td><td>地址</td>
	</tr>
	#foreach ($s in $listBean)	
		<tr>
		<td>$s.userId</td><td>$s.userName</td><td>$s.address</td>
		</tr>
	#end
</table>
</body>
</html>

2.在web-inf目錄下建立velocity.properties屬性檔案

Java程式碼 複製程式碼 收藏程式碼
  1. resource.loader = file
  2. file.resource.loader.path = /WEB-INF/velocity
  3. file.resource.loader.cache = true
  4. 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.建立Servlet檔案VelocityServletTest.java

Java程式碼 複製程式碼 收藏程式碼
  1. package servlet;
  2. import java.io.IOException;
  3. import java.io.StringWriter;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import javax.servlet.ServletConfig;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. import org.apache.commons.collections.ExtendedProperties;
  10. import org.apache.velocity.Template;
  11. import org.apache.velocity.app.Velocity;
  12. import org.apache.velocity.context.Context;
  13. import org.apache.velocity.tools.view.servlet.VelocityViewServlet;
  14. import com.test2.UserInfo;
  15. public class VelocityServletTest extends VelocityViewServlet{
  16. private static final long serialVersionUID = 1L;
  17. //第一步 載入配置檔案這個方法會在VelocityServlet的初始化方法init()中被呼叫
  18. protected ExtendedProperties loadConfiguration(ServletConfig config) throws IOException
  19. {
  20. ExtendedProperties p = super.loadConfiguration(config);
  21. // 獲取velocity.properties中配置的velocity模板路徑
  22. String velocityLoadPath = p.getString(Velocity.FILE_RESOURCE_LOADER_PATH);
  23. if (velocityLoadPath != null) {
  24. // 獲取模板路徑的絕對路徑
  25. velocityLoadPath = getServletContext().getRealPath(velocityLoadPath);
  26. if (velocityLoadPath != null) {
  27. //重新設定模板路徑
  28. System.out.println("vMPath2:"+velocityLoadPath);
  29. p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, velocityLoadPath);
  30. }
  31. }
  32. return p;
  33. }
  34. protected Template handleRequest(HttpServletRequest req,
  35. HttpServletResponse res,
  36. Context context)
  37. throws Exception{
  38. //字元編碼
  39. req.setCharacterEncoding("gb2312");
  40. res.setCharacterEncoding("gb2312");
  41. //頁面輸出
  42. res.setContentType("text/html;charset=" + "gb2312");
  43. List tempBean = new ArrayList();
  44. tempBean.add(new UserInfo("1","張三","福建"));
  45. tempBean.add(new UserInfo("2","李四","湖南"));
  46. context.put("listBean", tempBean);
  47. String templateName = "velocity.vm";
  48. // 測試資訊輸出
  49. Template t= getTemplate(templateName, "utf-8");
  50. StringWriter writer = new StringWriter();
  51. // 轉換輸出
  52. t.merge(context, writer);
  53. // 輸出資訊
  54. System.out.println(writer.toString());
  55. // 獲取模板頁面展示
  56. return templateName != null ? getTemplate(templateName, "utf-8") : null;
  57. }
  58. }
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;	
	
	//第一步 載入配置檔案這個方法會在VelocityServlet的初始化方法init()中被呼叫
    protected ExtendedProperties loadConfiguration(ServletConfig config) throws IOException
    {
        ExtendedProperties p = super.loadConfiguration(config);

        // 獲取velocity.properties中配置的velocity模板路徑
        String velocityLoadPath = p.getString(Velocity.FILE_RESOURCE_LOADER_PATH);        
   
        if (velocityLoadPath != null) {
        
        	// 獲取模板路徑的絕對路徑
        	velocityLoadPath = getServletContext().getRealPath(velocityLoadPath);
            if (velocityLoadPath != null) {
            	//重新設定模板路徑
            	 System.out.println("vMPath2:"+velocityLoadPath);
                p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, velocityLoadPath);               
            }
        }
        return p;
    }

	protected Template handleRequest(HttpServletRequest req, 
									 HttpServletResponse res, 
									 Context context)
									 throws Exception{
		
		//字元編碼
    	req.setCharacterEncoding("gb2312");
        res.setCharacterEncoding("gb2312");
        //頁面輸出
        res.setContentType("text/html;charset=" + "gb2312");
		
		List tempBean = new ArrayList();
		tempBean.add(new UserInfo("1","張三","福建"));
		tempBean.add(new UserInfo("2","李四","湖南"));
		context.put("listBean", tempBean);
		
	    String templateName = "velocity.vm";	    
	    // 測試資訊輸出
	    Template t= getTemplate(templateName, "utf-8");	    
		StringWriter writer = new StringWriter();
		// 轉換輸出
		t.merge(context, writer);
		// 輸出資訊
		System.out.println(writer.toString());	    
	    // 獲取模板頁面展示
            return templateName != null ? getTemplate(templateName, "utf-8") : null;		
	}
}

4.在web.xml檔案中進行配置

Xml程式碼 複製程式碼 收藏程式碼
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.4"
  3. xmlns="http://java.sun.com/xml/ns/j2ee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
  6. http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  7. <servlet>
  8. <servlet-name>velocityServletTest</servlet-name>
  9. <servlet-class>servlet.VelocityServletTest</servlet-class>
  10. <init-param>
  11. <param-name>org.apache.velocity.properties</param-name>
  12. <param-value>/WEB-INF/velocity.properties</param-value>
  13. </init-param>
  14. <load-on-startup>1</load-on-startup>
  15. </servlet>
  16. <servlet-mapping>
  17. <servlet-name>velocityServletTest</servlet-name>
  18. <url-pattern>/velocityServletTest</url-pattern>
  19. </servlet-mapping>
  20. </web-app>
<?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>
        <servlet-class>servlet.VelocityServletTest</servlet-class>
        <init-param>
            <param-name>org.apache.velocity.properties</param-name>
            <param-value>/WEB-INF/velocity.properties</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>velocityServletTest</servlet-name>
        <url-pattern>/velocityServletTest</url-pattern>
    </servlet-mapping>
</web-app>
Java程式碼 複製程式碼 收藏程式碼
  1. Hello Velocity World! 歡迎您~~~~~~~~~~~~
  2. ID 姓名 地址
  3. 1 張三 福建
  4. 2 李四 湖南
 Hello Velocity World! 歡迎您~~~~~~~~~~~~ 
 ID	姓名	地址
 1	張三	福建
 2	李四	湖南