`

Velocity 应用-文章链接

阅读更多

Webwork中使用Velocity入门实例

          使用说明:

             http://wiki.javascud.org/display/ww2cndoc/Velocity     2006-03-10

             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

 

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

             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

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

            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 :
        <html>
          <head><title>Sample velocity page</title></head>
          <body bgcolor="#ffffff">
            <center>
              <h2>Hello,welcome to velocity's world!</h2>
              <i>Here's the list of people</i>
              <table cellspacing="0" cellpadding="5" width="100%">
                <tr>
                  <td bgcolor="#eeeeee" align="center">Names</td>
                </tr>
                #foreach ($name in $theList)
                <tr>
                  <td bgcolor="#eeeeee">$name</td>
                </tr>
                #end
              </table>
            </center>
          </html>
          
    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 :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="WebApp">
 <display-name>VelocityAppWeb</display-name>
 <servlet>
  <servlet-name>SampleServlet</servlet-name>
  <display-name>SampleServlet</display-name>
  <servlet-class>com.cyberobject.study.velocity.servlet.SampleServlet</servlet-class>
  <init-param>
   <param-name>org.apache.velocity.properties</param-name>
   <param-value>/WEB-INF/classes/velocity.properties</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>SampleServlet</servlet-name>
  <url-pattern>/SampleServlet</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>
   三、发布及运行
    编译后,你可以发布到你熟悉的应用服务器中去,如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);参数名对应上即可。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics