Velocity 是如何工作的呢? 虽然大多 Velocity 的应用都是基于 Servlet 的网页制作。但是为了说明 Velocity 的使用,我决定采用更通用的 Java application 来说明它的工作原理。
似乎所有语言教学的开头都是采用 HelloWorld 来作为第一个程序的示例。这里也不例外。
模板文件:hello.vm中的内容为:Hello, $name
似乎所有语言教学的开头都是采用 HelloWorld 来作为第一个程序的示例。这里也不例外。
01 |
package com.makepolo.common.tools; |
02 |
03 |
import java.io.BufferedWriter; |
04 |
05 |
import java.io.OutputStreamWriter; |
06 |
07 |
import org.apache.velocity.Template; |
08 |
09 |
import org.apache.velocity.VelocityContext; |
10 |
11 |
import org.apache.velocity.app.Velocity; |
12 |
13 |
public class CreateType
{ |
14 |
15 |
public static void main(String[]
args) throws Exception
{ |
16 |
17 |
Velocity.init(); |
18 |
19 |
VelocityContext
context = new VelocityContext(); |
20 |
21 |
context.put("name","yy"); |
22 |
23 |
BufferedWriter
writer = new BufferedWriter(new OutputStreamWriter( |
24 |
System.out)); |
25 |
26 |
Template
template = Velocity.getTemplate("web/html/category/hello.vm"); |
27 |
28 |
template.merge(context,
writer); |
29 |
30 |
writer.flush(); |
31 |
32 |
writer.close(); |
33 |
34 |
} |
35 |
36 |
} |
注意:Template template = Velocity.getTemplate("web/html/category/hello.vm");
这句是模板 hello.vm 的存放位置;web 是工程目录;
参考:http://wenku.baidu.com/view/391fdd2531126edb6f1a102b.html
本文通过HelloWorld示例,详细介绍了如何使用Velocity框架在Java应用中生成动态页面,包括初始化Velocity、创建VelocityContext、加载模板文件以及将数据与模板合并的过程。

1503

被折叠的 条评论
为什么被折叠?



