站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Java 专题Velocity学习系列 之 Servlet应用

Velocity学习系列 之 Servlet应用

摘要: Velocity学习系列 之 Servlet应用

</td> </tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> 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) {}

<table width="674" border="0"> <tr> <td width="382">下面是例子(也是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
</td> <td width="282"> </td> </tr> </table>
这里我们使用了velocity.properties配置文件,通过这个文件我们可以灵活地进行一些运行期的配置, 本例中,我们指定了模板文件和日志文件的位置。

二、servlet类及相关文件编写
1、 Velocity配置文件 velocity.properties :

# 指定模板文件存放目录
file.resource.loader.path = templates
# 指定日志文件位置
runtime.log = log/velocity.log

注意一下:键的名字即key是固定的,具体请参考veloctiy开发指南。

2、 模板文件 sample.vm :

<head>Sample velocity page</head>
<body bgcolor="#ffffff">

Hello,welcome to velocity's world!


Here's the list of people
<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>



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;
/**
* @version 1.0
* @author
*/
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"?>
web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

VelocityAppWeb

SampleServlet
SampleServlet
com.cyberobject.study.velocity.servlet.SampleServlet

org.apache.velocity.properties
/WEB-INF/classes/velocity.properties

1


SampleServlet
/SampleServlet


index.jsp


三、发布及运行
编译后,你可以发布到你熟悉的应用服务器中去,如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);参数名对应上即可。


- 作者: kingwong 2004年08月28日,星期六 17:42:53
</td> </tr> <tr>


↑返回目录
前一篇: 屏蔽tomcat的目录列表功能
后一篇: 如何使用 velocity 模板引擎开发网站