基於java的Velocity模板匹配引擎
阿新 • • 發佈:2019-02-14
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.變數賦值輸出------------
- 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")
##這是一行註釋,不會輸出
#*這是多行註釋,不會輸出
多行註釋*#
// ---------- 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程式碼- ======text.txt====================
- this is test's content.yeah.
======text.txt====================
this is test's content.yeah.
3.客戶端應用測試程式碼:
Java程式碼- 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();
- }
- }
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程式碼- 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;
- }
- }
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程式碼- <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>
<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程式碼- 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.建立Servlet檔案VelocityServletTest.java
Java程式碼- 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;
- }
- }
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程式碼- <?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>
<?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程式碼
- Hello Velocity World! 歡迎您~~~~~~~~~~~~
- ID 姓名 地址
- 1 張三 福建
- 2 李四 湖南
Hello Velocity World! 歡迎您~~~~~~~~~~~~
ID 姓名 地址
1 張三 福建
2 李四 湖南