基于java的Velocity模板匹配引擎

时间:2025-02-15 10:35:12

Velocity是一个基于java的模板引擎(模板引擎的作用就是取得数据并加以处理,最后显示出数据)。
它允许任何人仅仅简单的使用模板语言来引用由java代码定义的对象。

主要应用在:
 应用的开发。
 2.作为模板产生SQL,XML或代码等。
 3.作为其他系统的集成组件使用。

当Velocity应用于application program或 a servlet,主要工作流程如下:
 1.初始化Velocity.
 2.创建Context对象
 3.添加数据到Context
 4.选择模板
 5.合并模板和数据产生输出页面

准备工作:导入相关依赖包,在下面附件中。

例1:应用程序事例

1.模板文件文件

Java代码
  1. ##这是一行注释,不会输出
  2. #*这是多行注释,不会输出
  3. 多行注释*#
  4. // ---------- 1.变量赋值输出------------
  5. Welcome $name to !
  6. today is $date.
  7. tdday is $mydae.//未被定义的变量将当成字符串
  8. // -----------2.设置变量值,所有变量都以$开头----------------
  9. #set( $iAmVariable = "good!" )
  10. Welcome $name to !
  11. today is $date.
  12. $iAmVariable
  13. //-------------,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 $() )
  27. $key ‘s value: $ ($key)
  28. #end
  29. //-----------6.迭代数据List Bean($velocityCount为列举序号,默认从1开始,可调整)
  30. #foreach ($s in $listBean)
  31. <$velocityCount> 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/")
##这是一行注释,不会输出
#*这是多行注释,不会输出
   多行注释*#
// ---------- 1.变量赋值输出------------
Welcome $name to !
today is $date.
tdday is $mydae.//未被定义的变量将当成字符串

// -----------2.设置变量值,所有变量都以$开头----------------
#set( $iAmVariable = "good!" )
Welcome $name to !
today is $date.
$iAmVariable

//-------------,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 $() )  
$key ‘s value: $ ($key)
#end

//-----------6.迭代数据List Bean($velocityCount为列举序号,默认从1开始,可调整)
#foreach ($s in $listBean)
<$velocityCount> 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/")

2.其它非模板文件

Java代码
  1. ==========================
  2. this is test's .
   ==========================
   this is test's .

3.客户端应用测试代码:

Java代码
  1. package com.test2;
  2. import ;
  3. import ;
  4. import .*;
  5. import ;
  6. import ;
  7. import ;
  8. import ;
  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. (Velocity.FILE_RESOURCE_LOADER_PATH, "D:/myspace/VelocityTest/src");
  16. (p);
  17. //取得velocity的模版
  18. Template t = ("com/test2/","utf-8");
  19. // 取得velocity的上下文context
  20. VelocityContext context = new VelocityContext();
  21. // 把数据填入上下文
  22. ("name", "Liang");
  23. ("date", (new Date()).toString());
  24. // 为后面的展示,提前输入List数值
  25. List temp = new ArrayList();
  26. ("item1");
  27. ("item2");
  28. ("list", temp);
  29. List tempBean = new ArrayList();
  30. (new UserInfo("1","张三","福建"));
  31. (new UserInfo("2","李四","湖南"));
  32. ("listBean", tempBean);
  33. // 输出流
  34. StringWriter writer = new StringWriter();
  35. // 转换输出
  36. (context, writer);
  37. // 输出信息
  38. (());
  39. // 输出到文件
  40. FileOutputStream of = new FileOutputStream("d:/");
  41. (().getBytes("GBK"));
  42. ();
  43. ();
  44. }
  45. }
package com.test2;
import ;
import ;
import .*;
import ;
import ;
import ;
import ;

public class HelloVelocity {

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

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

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

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

		// 把数据填入上下文
		("name", "Liang");
		("date", (new Date()).toString());

		// 为后面的展示,提前输入List数值
		List temp = new ArrayList();
		("item1");
		("item2");
		("list", temp);		
		List tempBean = new ArrayList();
		(new UserInfo("1","张三","福建"));
		(new UserInfo("2","李四","湖南"));
		("listBean", tempBean);

		// 输出流
		StringWriter writer = new StringWriter();
		// 转换输出
		(context, writer);
		// 输出信息
		(());
		
		// 输出到文件
		FileOutputStream of = new FileOutputStream("d:/");
                           (().getBytes("GBK")); 
                           ();
                           ();		
	}
}

实体类

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();
		 = userId;
		 = userName;
		 = address;
	}
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		 = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		 = userName;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		 = address;
	}
}

例2:Web应用事例

1.在web-inf目录下建立velocity目录,建立一模板文件。

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>$</td><td>$</td><td>$</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>$</td><td>$</td><td>$</td>
		</tr>
	#end
</table>
</body>
</html>

2.在web-inf目录下建立属性文件

Java代码
  1. = file
  2. = /WEB-INF/velocity
  3. = true
  4. = 300
 = file
 = /WEB-INF/velocity
 = true
 = 300

3.建立Servlet文件

Java代码
  1. package servlet;
  2. import ;
  3. import ;
  4. import ;
  5. import ;
  6. import ;
  7. import ;
  8. import ;
  9. import ;
  10. import ;
  11. import ;
  12. import ;
  13. import ;
  14. import com.;
  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模板路径
  22. String velocityLoadPath = (Velocity.FILE_RESOURCE_LOADER_PATH);
  23. if (velocityLoadPath != null) {
  24. // 获取模板路径的绝对路径
  25. velocityLoadPath = getServletContext().getRealPath(velocityLoadPath);
  26. if (velocityLoadPath != null) {
  27. //重新设置模板路径
  28. ("vMPath2:"+velocityLoadPath);
  29. (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. ("gb2312");
  40. ("gb2312");
  41. //页面输出
  42. ("text/html;charset=" + "gb2312");
  43. List tempBean = new ArrayList();
  44. (new UserInfo("1","张三","福建"));
  45. (new UserInfo("2","李四","湖南"));
  46. ("listBean", tempBean);
  47. String templateName = "";
  48. // 测试信息输出
  49. Template t= getTemplate(templateName, "utf-8");
  50. StringWriter writer = new StringWriter();
  51. // 转换输出
  52. (context, writer);
  53. // 输出信息
  54. (());
  55. // 获取模板页面展示
  56. return templateName != null ? getTemplate(templateName, "utf-8") : null;
  57. }
  58. }
package servlet;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import com.;

	public class VelocityServletTest extends VelocityViewServlet{
	
	private static final long serialVersionUID = 1L;	
	
	//第一步 加载配置文件这个方法会在VelocityServlet的初始化方法init()中被调用
    protected ExtendedProperties loadConfiguration(ServletConfig config) throws IOException
    {
        ExtendedProperties p = (config);

        // 获取中配置的velocity模板路径
        String velocityLoadPath = (Velocity.FILE_RESOURCE_LOADER_PATH);        
   
        if (velocityLoadPath != null) {
        
        	// 获取模板路径的绝对路径
        	velocityLoadPath = getServletContext().getRealPath(velocityLoadPath);
            if (velocityLoadPath != null) {
            	//重新设置模板路径
            	 ("vMPath2:"+velocityLoadPath);
                (Velocity.FILE_RESOURCE_LOADER_PATH, velocityLoadPath);               
            }
        }
        return p;
    }

	protected Template handleRequest(HttpServletRequest req, 
									 HttpServletResponse res, 
									 Context context)
									 throws Exception{
		
		//字符编码
    	("gb2312");
        ("gb2312");
        //页面输出
        ("text/html;charset=" + "gb2312");
		
		List tempBean = new ArrayList();
		(new UserInfo("1","张三","福建"));
		(new UserInfo("2","李四","湖南"));
		("listBean", tempBean);
		
	    String templateName = "";	    
	    // 测试信息输出
	    Template t= getTemplate(templateName, "utf-8");	    
		StringWriter writer = new StringWriter();
		// 转换输出
		(context, writer);
		// 输出信息
		(());	    
	    // 获取模板页面展示
            return templateName != null ? getTemplate(templateName, "utf-8") : null;		
	}
}

4.在文件中进行配置

Xml代码
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.4"
  3. xmlns="/xml/ns/j2ee"
  4. xmlns:xsi="http:///2001/XMLSchema-instance"
  5. xsi:schemaLocation="/xml/ns/j2ee
  6. /xml/ns/j2ee/web-app_2_4.xsd">
  7. <servlet>
  8. <servlet-name>velocityServletTest</servlet-name>
  9. <servlet-class></servlet-class>
  10. <init-param>
  11. <param-name></param-name>
  12. <param-value>/WEB-INF/</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="/xml/ns/j2ee" 
	xmlns:xsi="http:///2001/XMLSchema-instance" 
	xsi:schemaLocation="/xml/ns/j2ee 
	/xml/ns/j2ee/web-app_2_4.xsd">
	
	<servlet>
        <servlet-name>velocityServletTest</servlet-name>
        <servlet-class></servlet-class>
        <init-param>
            <param-name></param-name>
            <param-value>/WEB-INF/</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>

5.将其部署到tomcat下,页面访问
http://localhost:8080/VelocityTest/velocityServletTest
输出页面如下:

Java代码
  1. Hello Velocity World! 欢迎您~~~~~~~~~~~~
  2. ID 姓名 地址
  3. 1 张三 福建
  4. 2 李四 湖南
 Hello Velocity World! 欢迎您~~~~~~~~~~~~ 
 ID	姓名	地址
 1	张三	福建
 2	李四	湖南