之前的文章《Velocity初體驗(yàn)》,介紹了Velocity的工作原理和一些演示樣例,但有朋友覺得不和Web結(jié)合起來針對(duì)性不夠突出,所以下面結(jié)合Web開發(fā)來進(jìn)一步說明,Velocity+Servlet(+JavaBean)是怎樣工作的。
通過下面的說明,僅提出Velocity在Web方面的簡(jiǎn)單示例,為大家獻(xiàn)上一個(gè)原始但清晰的認(rèn)識(shí),來了解Velocity在Web方面的工作原理,未來還有深入的主題貢獻(xiàn)給大家。
Web環(huán)境要求Tomcat,我是用5.5版本。
首先我們還是使用VTL(Velocity Template Language)編一個(gè).vm模版,考察在網(wǎng)頁設(shè)計(jì)師的角度是不是很容易理解和編輯,首先創(chuàng)建sample.vm內(nèi)容如下:
< html >
< head >< title > Velocity </ title ></ head >
< body bgcolor = " #ffffff " >
< center >
< h2 > Welcom to Velocity !</ h2 >
< i > Here ‘ s the list of people</i>
< table cellspacing = " 0 " cellpadding = " 5 " width = " 20% " >
< tr >
< td bgcolor = " #eeeeee " align = " center " >
Names:
</ td >
</ tr >
#foreach ($name in $theList)
< tr >
< td bgcolor = " #eeeeee " align = " center " > $name </ td >
</ tr >
#end
</ table >
</ center >
</ body >
</ html >
然后打開FrontPage(或其他類似工具)網(wǎng)頁編輯器,點(diǎn)擊"工具-選項(xiàng)-配置編輯器",上面列出了FrontPage能打開的文件,點(diǎn)擊添加,填入文件類型:vm,編輯器名稱:FrontPage,命令:C:\Program Files\Microsoft Office\Office\frontpg.exe(FrontPage運(yùn)行的完整路徑,可從已有的文件類型中Copy出完整路徑),點(diǎn)擊打開界面的確定后,我們從FrontPage的文件菜單中選擇打開文件,選擇上面新建的sample.vm,怎么樣,編輯、預(yù)覽和修改都一目了然吧(如下圖),即使不清楚VTL的,也可以通過簡(jiǎn)單的手冊(cè)查詢知道(一般都不會(huì)用到吧),這樣對(duì)于網(wǎng)頁設(shè)計(jì)師、開發(fā)人員和維護(hù)人員來說,都是很容易的事。而如果你使用了一些開發(fā)工具,如Jbuilder則在tools-proference的編輯類型里,在Html檔增加.vm的支持,則就可以進(jìn)行編輯和用html預(yù)覽器預(yù)覽了,其他的開發(fā)工具自己摸索吧。
接下來看看最簡(jiǎn)單的Servlet是怎么和Velocity結(jié)合工作的,創(chuàng)建SampleServlet.java,由于VelocityServlet提供了統(tǒng)一的Servlet入口和封裝了大部分工作,以及把展示數(shù)據(jù)合并到模版中,所以SampleServlet通過繼承VelocityServlet,工作將簡(jiǎn)便很多,代碼如下:
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()調(diào)用, 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 );
// 同樣設(shè)置log
p.setProperty( " runtime.log " , path + " velocity.log " );
return p;
}
/** */ /**
* Velocity主要的商業(yè)邏輯處理方法,由VelocityServlet自動(dòng)調(diào)用
* @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 ) {
// 主要在此設(shè)置演示用的數(shù)據(jù),開發(fā)中在此調(diào)用相應(yīng)的業(yè)務(wù)處理流程,
// 并設(shè)置返回到頁面的數(shù)據(jù)
System.out.println( " ------SampleVelocity.handleRequest------- " );
// 待展示的列表數(shù)據(jù)
String p1 = " 第一位:LiuDong " ;
String p2 = " 第二位:Liang.xf " ;
Vector personList = new Vector();
// 中文需要轉(zhuǎn)換
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( " 數(shù)據(jù)轉(zhuǎn)換異常: " + e);
}
// 設(shè)置數(shù)據(jù),供頁面模版替換成顯示的數(shù)據(jù)
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
編譯通過后,我們接著需要發(fā)布了,以Tomcat5.5為例,新建Web應(yīng)用簡(jiǎn)易說明如下:
1、\tomcat55\webapps目錄下新建目錄test,把上述sample.vm Copy進(jìn)test目錄,在test內(nèi)新建目錄WEB-INF,在WEB-INF內(nèi)分別新建目錄:classes和lib,在WEB-INF目錄下新建文件web.xml,內(nèi)容:
<? xml version = " 1.0 " encoding = " ISO-8859-1 " ?>
< web - app >
< display - name > Welcome to Javayou.com </ display - name >
< servlet >
< servlet - name > SampleServlet </ servlet - name >
< servlet - class > com.javayou.velocity.servlet.SampleServlet </ servlet - class >
</ servlet >
< servlet - mapping >
< servlet - name > SampleServlet </ servlet - name >
< url - pattern >/ SampleServlet </ url - pattern >
</ servlet - mapping >
</ web - app > 2、在classes內(nèi)建立類包目錄:com\javayou\velocity\servlet\,copy上面編譯后的SampleServlet.class;
3、在lib目錄內(nèi)分別copy進(jìn):commons-collections.jar、logkit-1.0.1.jar、velocity-1.4.jar;
OK,Tomcat運(yùn)行環(huán)境搭建完畢。
啟動(dòng)Tomcat,在IE上輸入:http://localhost:8080/test/SampleServlet,頁面顯示和數(shù)據(jù)列表:第一位:LiuDong、第二位:Liang.xf 2正確,大功告成!
注意上面的顯示數(shù)據(jù)含中文,所以在設(shè)置進(jìn)裝載容器時(shí)注意進(jìn)行編碼,稍顯麻煩,這可以用更自動(dòng)化的辦法,如使用Util工具類等。
以上看來Servlet+Velocity的結(jié)合還是挺容易和簡(jiǎn)單的,而至于引伸到Servlet+Velocity+JavaBean 也不是很困難的事,稍為擴(kuò)展即可達(dá)到,在這里就不再多述。