日期:2014-05-16  浏览次数:20727 次

Velocity模版与Ajax灵活应用

一:先简单介绍一下velocity的模版页面

velocity是apache开源组织旗下的一个开源项目,可以到apache的官方网去下载并了解它的语法和用法,非常简单,既方便又易用,主要包括两个jar包,velocity-1.5.jar,velocity-dep-1.5.jar。

velocity的模版是以vm为后缀的,例如我的web应用下有一个模版:/myweb/template/test.vm,它是以$符号来引用 对象,例如我在request中设置了一个名称叫做mydata的attribute,类型为List,list的保存的对象类型为Data.java

public class Data {
private String name = "";
private String sex = "";
private String address = "";
public String getAddress() {
?? return address;
}
public void setAddress(String address) {
?? this.address = address;
}
public String getName() {
?? return name;
}
public void setName(String name) {
?? this.name = name;
}
public String getSex() {
?? return sex;
}
public void setSex(String sex) {
?? this.sex = sex;
}
}

在页面显示时的迭代用法是:

<table>
<tr>
#foreach($data in $!mydata)
<td>$!data.getName()</td>
<td>$!data.getSex()</td>
<td>$!data.getAddress()</td>
#end
</tr>
</table>

用模版犹如建一栋房子,把钢架结构搭好了,就往里边堆东西就可以了。

二:解析velocity模版的实现说明

Velocity引擎对vm模版解释是根据引擎的上下文和模版的路径来进行解析的,从以下的代码可以一览其然,非常简单明了:

首先要初始化一个vm引擎:

?? VelocityEngine engine = new VelocityEngine();

再次要初始化vm模版资源的绝对路径,以方便引擎进行解析(黑体部分的属性是必须得有的,vm模版的路径例如第一点中的:/myweb/template/test.vm:):

Properties p = new Properties();
??? final String str = vmpath.substring(0, vmpath.lastIndexOf("/"));

??? p.setProperty("file.resource.path", request.getSession()
????? .getServletContext().getRealPath("")
????? + str);
??? engine.init(p);

然后就是把request属性等设置在引擎的上下文中,当然也可以把session中的属性也设置进去。

VelocityContext context = new VelocityContext();
?? Enumeration enu = request.getAttributeNames();

?? while (enu.hasMoreElements()) {
??? final String paramName = enu.nextElement().toString();
??? context.put(paramName, request.getAttribute(paramName));
?? }

最后就是解析模版了:

??? template = engine.getTemplate(vmpath.substring(vmpath
????? .lastIndexOf("/") + 1));
??? template.merge(context, sw);

以下是解析vm模版的全部代码:

import java.io.StringWriter;
import java.util.Enumeration;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

public class VmUtil {

public static String getVmString(HttpServletRequest request, String vmpath) {
?? if (null == vmpath || "".equals(vmpath))
??? return "";

?? // velocity模版的解析引擎
?? VelocityEngine engine = new VelocityEngine();

?? try {
??? Properties p = new Properties();
??? final String str = vmpath.substring(0, vmpath.lastIndexOf("/"));

??? p.setProperty("file.resource.path", request.getSession()
????? .getServletContext().getRealPath("")
????? + str);
??? engine.init(p);
??