基于java的Velocity模板匹配引擎

来源:互联网 发布:淘宝提升流量的方法 编辑:程序博客网 时间:2024/06/03 03:03

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!#elseWelcome 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.#endouter: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的上下文contextVelocityContext 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 = filefile.resource.loader.path = /WEB-INF/velocityfile.resource.loader.cache = truefile.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 VelocityServletTestextends 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>

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

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

  • velocity.rar (1.5 MB)
  • 下载次数: 93