Velocity之Web實踐

之前的文章《Velocity初體驗》,介紹了Velocity的工作原理和一些演示樣例,但有朋友覺得不和Web結合起來針對性不夠突出,所以下面結合Web開發來進一步說明,Velocity+Servlet(+JavaBean)是怎樣工作的。

通過下面的說明,僅提出Velocity在Web方面的簡單示例,爲大家獻上一個原始但清晰的認識,來了解Velocity在Web方面的工作原理,未來還有深入的主題貢獻給大家。

Web環境要求Tomcat,我是用5.5版本。

首先我們還是使用VTL(Velocity Template Language)編一個.vm模版,考察在網頁設計師的角度是不是很容易理解和編輯,首先創建sample.vm內容如下:

 
 
   


   

Welcom to Velocity!


    Here's the list of people
   

    Names:
   
$name

   

 

 

 

然後打開FrontPage(或其他類似工具)網頁編輯器,點擊"工具-選項-配置編輯器",上面列出了FrontPage能打開的文件,點擊添加,填入文件類型:vm,編輯器名稱:FrontPage,命令:C:/Program Files/Microsoft Office/Office/frontpg.exe(FrontPage運行的完整路徑,可從已有的文件類型中Copy出完整路徑),點擊打開界面的確定後,我們從FrontPage的文件菜單中選擇打開文件,選擇上面新建的sample.vm,怎麼樣,編輯、預覽和修改都一目瞭然吧(如下圖),即使不清楚VTL的,也可以通過簡單的手冊查詢知道(一般都不會用到吧),這樣對於網頁設計師、開發人員和維護人員來說,都是很容易的事。而如果你使用了一些開發工具,如Jbuilder則在tools-proference的編輯類型裏,在Html檔增加.vm的支持,則就可以進行編輯和用html預覽器預覽了,其他的開發工具自己摸索吧。

接下來看看最簡單的Servlet是怎麼和Velocity結合工作的,創建SampleServlet.java,由於VelocityServlet提供了統一的Servlet入口和封裝了大部分工作,以及把展示數據合併到模版中,所以SampleServlet通過繼承VelocityServlet,工作將簡便很多,代碼如下:

package com.javayou.velocity.servlet;

/*
 * @author Liang.xf 2004-12-15
 * Velocity + Servlet 演示
 * www.javayou.com
 */

import java.io.IOException;
import java.io.FileNotFoundException;

import java.util.Properties;
import java.util.Vector;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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 {
    /**
     *   由VelocityServlet.init()調用, We want to set a set of properties
     *   在此找出模版的路徑
     */
    protected Properties loadConfiguration(ServletConfig config )
        throws IOException, FileNotFoundException {
        Properties p = new Properties();
        /*
         *  first, we set the template path for the
         *  FileResourceLoader to the root of the
         *  webapp.  This probably won't work under
         *  in a WAR under WebLogic, but should
         *  under tomcat :)
         */
        String path = config.getServletContext().getRealPath("/");

        if (path == null) {
            System.out.println(" SampleServlet.loadConfiguration() : unable to "
                    + "get the current webapp root.  Using '/'. Please fix.");
            path = "/";
        }

        p.setProperty( Velocity.FILE_RESOURCE_LOADER_PATH,  path );
        //同樣設置log
        p.setProperty( "runtime.log", path + "velocity.log" );
        return p;
    }

    /**
     *  Velocity主要的商業邏輯處理方法,由VelocityServlet自動調用
     *  @param ctx a Velocity Context object to be filled with
     *             data.  Will be used for rendering this
     *             template
     *  @return Template to be used for request
     */  
    public Template handleRequest( HttpServletRequest request,
       HttpServletResponse response, Context ctx ) {
       
        //主要在此設置演示用的數據,開發中在此調用相應的業務處理流程,

        //       並設置返回到頁面的數據
       
        System.out.println("------SampleVelocity.handleRequest-------");
        //待展示的列表數據
        String p1 = "第一位:LiuDong";
        String p2 = "第二位:Liang.xf";
        Vector personList = new Vector();
        //中文需要轉換
        try {
            personList.addElement(new String(p1.getBytes(), "ISO-8859-1") );
            personList.addElement(new String(p2.getBytes(), "ISO-8859-1") );
        } catch (Exception e) {
            System.out.println("數據轉換異常:"+e);   
        }
        //設置數據,供頁面模版替換成顯示的數據
        ctx.put("theList", personList );       
        /*
         *  get the template.  There are three possible
         *  exceptions.  Good to know what happened.
         */
        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;
    }
}

編譯需要velocity-1.4.jar和j2ee.jar,這裏演示手工編譯命令(所有資源放在同一目錄):
javac -classpath ./velocity-1.4.jar;./j2ee.jar SampleServlet.java

編譯通過後,我們接着需要發佈了,以Tomcat5.5爲例,新建Web應用簡易說明如下:
1、/tomcat55/webapps目錄下新建目錄test,把上述sample.vm Copy進test目錄,在test內新建目錄WEB-INF,在WEB-INF內分別新建目錄:classes和lib,在WEB-INF目錄下新建文件web.xml,內容:


  Welcome to Javayou.com
 
     SampleServlet
     com.javayou.velocity.servlet.SampleServlet
 
 
      SampleServlet
      /SampleServlet
 

2、在classes內建立類包目錄:com/javayou/velocity/servlet/,copy上面編譯後的SampleServlet.class;
3、在lib目錄內分別copy進:commons-collections.jar、logkit-1.0.1.jar、velocity-1.4.jar;
OK,Tomcat運行環境搭建完畢。
啓動Tomcat,在IE上輸入:http://localhost:8080/test/SampleServlet,頁面顯示和數據列表:第一位:LiuDong、第二位:Liang.xf 2正確,大功告成!
注意上面的顯示數據含中文,所以在設置進裝載容器時注意進行編碼,稍顯麻煩,這可以用更自動化的辦法,如使用Util工具類等。
以上看來Servlet+Velocity的結合還是挺容易和簡單的,而至於引伸到Servlet+Velocity+JavaBean 也不是很困難的事,稍爲擴展即可達到,在這裏就不再多述。

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章