---
title: "Velocity 应用-文章链接"
author: "conect"
date: "2008-05-30T20:11:58Z"
tags: []
slug: "velocity"
draft: false
lastmod: "2008-05-30T20:11:58Z"
id: 198817
url: "https://conect.iteye.com/blog/198817"
---

Webwork中使用Velocity入门实例

          使用说明：

             [http://wiki.javascud.org/display/ww2cndoc/Velocity](http://wiki.javascud.org/display/ww2cndoc/Velocity)     2006-03-10

             [http://esffor.iteye.com/blog/96229](http://esffor.iteye.com/blog/96229)                          2007-04-12

 

      Sing Li  使用 Velocity 实现客户端和服务器端模板             2004-03 -13

             [http://www.ibm.com/developerworks/cn/java/j-velocity/#main](http://www.ibm.com/developerworks/cn/java/j-velocity/#main)

 

      让复杂的html表格在Apache Velocity中变得简单\[译](1)       2008-01-09

             [http://www.easyjf.com/blog/html/20080109/1015823.html](http://www.easyjf.com/blog/html/20080109/1015823.html)  

      让复杂的html表格在Apache Velocity中变得简单\[译](2)       2008-01-09

             [http://www.easyjf.com/blog/html/20080109/1015824.html](http://www.easyjf.com/blog/html/20080109/1015824.html)

       让复杂的html表格在Apache Velocity中变得简单\[译](3)      2008-01-09

            [http://www.easyjf.com/blog/html/20080109/1048576.html](http://www.easyjf.com/blog/html/20080109/1048576.html)

Velocity学习之 Servlet应用  
   
    在基于WEB的应用中，通常大多数情况下是在servlet里使用Velocity。在servlet里的Velocity基本应用是非常简单的，你只需通过两个必要步骤就可以实现：

    一、继承org.apache.velocity.servlet.VelocityServlet抽象类：   
public class SampleServlet extends VelocityServlet

    二、仅需实现VelocityServlet类的一个方法handleRequest()：   
public Template handleRequest( HttpServletRequest req, HttpServletResponse resp, Context context) {}  
下面是例子(也是Velocity发行包自带的例子)。  
    一、准备工作  
    本例按如下结构建立一个web应用：  
    VelocityAppWeb  
    |\_\_\_\_log  
    |\_\_\_\_templates  
    |        |\_\_\_\_sample.vm  
    |\_\_\_\_WEB\_INF  
             |\_\_\_\_classes  
             |        |\_\_\_\_your\_full\_path\_servlet.class  
             |        |\_\_\_\_velocity.properties  
             |\_\_\_\_lib  
             |        |\_\_\_\_velocity-dep-1.4.jar  
             |\_\_\_\_web.xml  
这里我们使用了velocity.properties配置文件，通过这个文件我们可以灵活地进行一些运行期的配置， 本例中，我们指定了模板文件和日志文件的位置。  
      
    二、servlet类及相关文件编写  
    1、 Velocity配置文件 velocity.properties :  
       
           # 指定模板文件存放目录      
           file.resource.loader.path = templates  
           # 指定日志文件位置  
           runtime.log = log/velocity.log  
      
           注意一下：键的名字即key是固定的，具体请参考veloctiy开发指南。  
      
    2、 模板文件 sample.vm :  
        &lt;html&gt;  
          &lt;head&gt;&lt;title&gt;Sample velocity page&lt;/title&gt;&lt;/head&gt;  
          &lt;body bgcolor="#ffffff"&gt;  
            &lt;center&gt;  
              &lt;h2&gt;Hello,welcome to velocity's world!&lt;/h2&gt;  
              &lt;i&gt;Here's the list of people&lt;/i&gt;  
              &lt;table cellspacing="0" cellpadding="5" width="100%"&gt;  
                &lt;tr&gt;  
                  &lt;td bgcolor="#eeeeee" align="center"&gt;Names&lt;/td&gt;  
                &lt;/tr&gt;  
                #foreach ($name in $theList)  
                &lt;tr&gt;  
                  &lt;td bgcolor="#eeeeee"&gt;$name&lt;/td&gt;  
                &lt;/tr&gt;  
                #end  
              &lt;/table&gt;  
            &lt;/center&gt;  
          &lt;/html&gt;  
            
    3、servlet类 SampleServlet.java :  
package com.cyberobject.study.velocity.servlet;

import java.io.IOException;  
import java.io.FileNotFoundException;  
import java.io.FileInputStream;  
import java.util.Properties;  
import java.util.Vector;  
import javax.servlet.ServletConfig;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.ServletException;  
import org.apache.velocity.Template;  
import org.apache.velocity.context.Context;  
import org.apache.velocity.servlet.VelocityServlet;  
import org.apache.velocity.app.Velocity;  
import org.apache.velocity.exception.ResourceNotFoundException;  
import org.apache.velocity.exception.ParseErrorException;

public class SampleServlet extends VelocityServlet  
{  
     protected Properties loadConfiguration(ServletConfig config)throws IOException, FileNotFoundException{  
  /*  
   *  得到属性配置文件并load它  
   \*/  
     String propsFile = config.getInitParameter(INIT\_PROPS\_KEY);  
     Properties p = new Properties();  
     if (propsFile != null){  
       String realPath = getServletContext().getRealPath(propsFile);  
     if (realPath != null){  
         propsFile = realPath;  
      }  
    p.load(new FileInputStream(propsFile));  
  }  
  /*  
   *  设置velocity日志文件在web应用中的位置  
   \*/  
     String log = p.getProperty(Velocity.RUNTIME\_LOG);  
     if (log != null){  
        log = getServletContext().getRealPath(log);  
     if (log != null)   {  
        p.setProperty(Velocity.RUNTIME\_LOG, log);  
     }  
  }  
  /*  
   *  设置模板文件在web应用中的位置  
   \*/  
     String path = p.getProperty(Velocity.FILE\_RESOURCE\_LOADER\_PATH);  
     if (path != null){  
     path = getServletContext().getRealPath(path);  
     if (path != null){  
        p.setProperty(Velocity.FILE\_RESOURCE\_LOADER\_PATH, path);  
     }  
  }  
  return p;  
 }

   public Template handleRequest (HttpServletRequest request,HttpServletResponse response,Context ctx){  
  String p1 = "Bob";  
  String p2 = "Harold";  
  Vector personList = new Vector();  
  personList.addElement(p1);  
  personList.addElement(p2);  
  /*  
   *  将模板数据 list 放置到上下文环境 context 中去  
   \*/  
  ctx.put("theList", personList);  
  /*  
   *  获取模板对象，有三种可能产生的异常  
   \*/  
  Template outty = null;  
  try{  
          outty = getTemplate("sample.vm");  
       } catch (ParseErrorException pee){  
         System.out.println(  
            "SampleServlet : parse error for template " + pee);  
       }catch (ResourceNotFoundException rnfe){  
          System.out.println("SampleServlet : template not found " + rnfe);  
       }catch (Exception e){  
         System.out.println("Error " + e);  
    }  
    return outty;  
   }  
}  
    4、 Web应用程序配置文件 web.xml :  
&lt;?xml version="1.0" encoding="UTF-8"?&gt;  
&lt;!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app\_2\_3.dtd"&gt;  
&lt;web-app id="WebApp"&gt;  
 &lt;display-name&gt;VelocityAppWeb&lt;/display-name&gt;  
 &lt;servlet&gt;  
  &lt;servlet-name&gt;SampleServlet&lt;/servlet-name&gt;  
  &lt;display-name&gt;SampleServlet&lt;/display-name&gt;  
  &lt;servlet-class&gt;com.cyberobject.study.velocity.servlet.SampleServlet&lt;/servlet-class&gt;  
  &lt;init-param&gt;  
   &lt;param-name&gt;org.apache.velocity.properties&lt;/param-name&gt;  
   &lt;param-value&gt;/WEB-INF/classes/velocity.properties&lt;/param-value&gt;  
  &lt;/init-param&gt;  
  &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;  
 &lt;/servlet&gt;  
 &lt;servlet-mapping&gt;  
  &lt;servlet-name&gt;SampleServlet&lt;/servlet-name&gt;  
  &lt;url-pattern&gt;/SampleServlet&lt;/url-pattern&gt;  
 &lt;/servlet-mapping&gt;  
 &lt;welcome-file-list&gt;  
  &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;  
 &lt;/welcome-file-list&gt;  
&lt;/web-app&gt;  
   三、发布及运行  
    编译后，你可以发布到你熟悉的应用服务器中去，如Tomcat等。启动服务器，在浏览器中输入：http://localhost:8080/VelocityAppWeb/servlet/SampleServlet，可看到如下结果：(略,请下载源文件运行）

    在servlet中使用Velocity的步骤和在独立应用程序中是基本相似的:  
        1、获得并初始化一个模板引擎；  
        2、以模板文件名为参数，调用getTemplate()得到一个模板对象；  
        3、创建一个上下文环境对象，并将模板数据放入上下文环境中；  
        4、合并（merge）模板和数据并产生一个输出。  
    事实上，有很多步骤如1、4，VelocityServlet基类都已经帮我们做了，就连3中的创建上下文环境对象都已经代劳了，你所要做的仅仅是通过指定模板文件名获得一个模板对象和将数据put到上下文中去，还是很简单吧？！呵呵。  
      
    注意事项：  
        1、不要在servlet中实现doGet()和doPost()方法。VelocityServlet已经帮你完成了。  
        2、web.xml文件中SampleServlet的初始化参数name的写法：  org.apache.velocity.properties,这是固定的，它是VelocityServlet中的常量INIT\_PROPS\_KEY对应的值。当然如果在你的servlet中loadConfiguration()方法中不使用该常量名时，你也可以随便取名，只要和这里的  
        String propsFile = config.getInitParameter(INIT\_PROPS\_KEY);参数名对应上即可。