本文讲解了velocity主要的模板方法,会了这些方法基本上就会了velocity。同时本java工程是用maven管理,(maven的使用,大家可以看我的另一篇文章)。用到的是1.7版本。代码如下:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cloud</groupId> <artifactId>velocity_01</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>velocity_01</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> </dependencies> </project>
测试当中要用到的两个model类:
Person.java:
package com.cloud.velocity.model;
public class Person {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person() {}
public Person(int id, String name) {
this.id = id;
this.name = name;
}
}
Product.java
package com.cloud.velocity.model;
public class Product {
private String id;
private String name;
private String note;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Product() {
}
public Product(String id, String name, String note) {
this.id = id;
this.name = name;
this.note = note;
}
}
用到的工具类:
DateUtil.java
package com.cloud.velocity.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
public String dateFormat(String formatStr, Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
return sdf.format(date);
}
}
Velocity的配置文件:
velocity.properties
file.resource.loader.path=D:\\neil\\hadoop_workspace\\velocity_01\\src\\main\\resources
input.encoding=UTF-8
output.encoding=UTF-8
directive.foreach.counter.name=index
directive.foreach.counter.initial.value=0
各种模板文件:
helloWorld.vm
${hello}
person.vm
${p.id} = ${p.name}
persons.vm
#foreach($person in $persons)
$person.id = $person.name
#end
maps.vm
#foreach($key in $maps.keySet())
$index = $key = $maps.get($key)
#end
================================
#foreach($entry in $maps.entrySet())
$entry.getKey() = $entry.getValue()
#end
pageSet.vm
#set($name="cloud")
$name
===================
#set($age=22)
$age
===================
#set($arrs=["chris", "cloud"])
#foreach($arr in $arrs)
$arr
#end
====================
#set($ints=[1..15])
#foreach($int in $ints)
$int
#end
ifelse.vm
#if($bool)
Is true
#else
Is false
#end
date.vm
$dateFormat.dateFormat("yyyy-MM-dd HH:mm:ss", $now)
html.vm
<html>
<head>
<title>$product.name -- Cloud</title>
</head>
<body>
<h1>$product.name</h1>
<br />
<div>
Note:$product.note
</div>
</body>
</html>
最重要的测试类:
VelocityTest.java
package com.cloud.velocity.test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.BeforeClass;
import org.junit.Test;
import com.cloud.velocity.model.Person;
import com.cloud.velocity.model.Product;
import com.cloud.velocity.utils.DateUtil;
public class VelocityTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
/**
* 其中helloWorld.vm中的格式为:${hello},即此种情况是最简单的,单元测试的结果
* 就是将"Cloud, 您好!!!"原样输出。
*/
@Test
public void test() {
Velocity.init("src/main/resources/velocity.properties");
VelocityContext context = new VelocityContext();
context.put("hello", "Cloud, 您好!!!");
Template template = Velocity.getTemplate("helloWorld.vm");
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
}
/**
* 这里测试的情况为:如何将一个JavaBean中的内容在模板中显示出来。
* person.vm中内容为:${p.id} = ${p.name}
* 单元测试结果:22 = cloud
*/
@Test
public void testBean() {
Velocity.init("src/main/resources/velocity.properties");
VelocityContext context = new VelocityContext();
context.put("p", new Person(22, "cloud"));
Template template = Velocity.getTemplate("person.vm");
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
}
/**
* 这里测试的情况为:在模板中如何迭代一个list集合(数组也是一样的)。
* persons.vm中的内容为:
* #foreach($person in $persons)
* $person.id = $person.name
* #end
* 单元测试的结果为:
* 22 = cloud
* 23 = chris
*/
@Test
public void loopList() {
Velocity.init("src/main/resources/velocity.properties");
VelocityContext context = new VelocityContext();
context.put("persons", new Person[] {new Person(22, "cloud"), new Person(23, "chris")});
Template template = Velocity.getTemplate("persons.vm");
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
}
/**
* 这里测试的情况为:在模板中如何迭代一个map集合。
* maps.vm中的内容为:
* #foreach($key in $maps.keySet())
* $index = $key = $maps.get($key)
* #end
*
* ================================
* #foreach($entry in $maps.entrySet())
* $entry.getKey() = $entry.getValue()
* #end
* 其实这里是列出在模板中显示map集合内容的两种方法。其中$index是一个计数器。它的配置是在velocity.properties中
* directive.foreach.counter.name=index //这里配置了计数器的名字:即为index,默认的为:velocityCount。
* directive.foreach.counter.initial.value=0 //这里是设置计数器的起始值,即为0。默认为:1。
* 单元测试的结果为:
* 0 = 22 = cloud
* 1 = 23 = chris
*
* ================================
* 22 = cloud
* 23 = chris
*/
@Test
public void loopMap() {
Velocity.init("src/main/resources/velocity.properties");
VelocityContext context = new VelocityContext();
Map<String, String> maps = new HashMap<String, String>();
maps.put("22", "cloud");
maps.put("23", "chris");
context.put("maps", maps);
Template template = Velocity.getTemplate("maps.vm");
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
}
/**
* 这里测试的情况为:为模板中的变量赋值。
* pageSet.vm中内容为:
* #set($name="cloud")
* $name
* ===================
* #set($age=22)
* $age
* ===================
* #set($arrs=["chris", "cloud"])
* #foreach($arr in $arrs)
* $arr
* #end
* ====================
* #set($ints=[1..15])
* #foreach($int in $ints)
* $int
* #end
* 测试结果为:
* cloud
* ====================
* 22
* ====================
* chris
* cloud
* ====================
* 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 //此处的显示效果应为:竖着显示的,为了节约空间,在此就横着写了。
*注意:$ints=[1..15]这种赋值形式是为:为这个变量赋值连续的变量。
*
*/
@Test
public void pageSet() {
Velocity.init("src/main/resources/velocity.properties");
VelocityContext context = new VelocityContext();
Template template = Velocity.getTemplate("pageSet.vm");
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
}
/**
* 这里测试的是在模板中如何用条件判断语句。
* ifelse.vm内容为:
* #if($bool)
* Is true
* #else
* Is false
* #end
* 单元测试结果为:
* Is false
*/
@Test
public void ifelse() {
Velocity.init("src/main/resources/velocity.properties");
VelocityContext context = new VelocityContext();
context.put("bool", false);
Template template = Velocity.getTemplate("ifelse.vm");
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
}
/**
* 这里测试的结果为:如何在模板中按特定的格式显示出日期。
* 我在此没有去使用第三方jar包,而是利用velocity有很好的
* 扩展功能实现的。
* 在我写了一个DateUtil工具类。
* date.vm的内容为:
* $dateFormat.dateFormat("yyyy-MM-dd HH:mm:ss", $now)
* 单元测试结果为:
* 2013-11-10 10:43:22
*/
@Test
public void dateFormat() {
Velocity.init("src/main/resources/velocity.properties");
VelocityContext context = new VelocityContext();
context.put("now", new Date());
context.put("dateFormat", new DateUtil());
Template template = Velocity.getTemplate("date.vm");
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
}
/**
* 这里实现的功能是:将模板中的内容输出到一个文件当中。
*/
@Test
public void outFile() {
try {
Velocity.init("src/main/resources/velocity.properties");
Product product = new Product("p0010", "cloud", "Good job!");
VelocityContext context = new VelocityContext();
context.put("product", product);
Template template = Velocity.getTemplate("html.vm");
File saveFile = new File("src/main/html/product.html");
if (!saveFile.getParentFile().exists()) {
saveFile.getParentFile().mkdirs();
}
FileOutputStream outStream = new FileOutputStream(saveFile);
OutputStreamWriter outStreamWriter = new OutputStreamWriter(outStream, "UTF-8");
BufferedWriter writer = new BufferedWriter(outStreamWriter);
template.merge(context, writer);
writer.flush();
writer.close();
} catch (Exception e) {
}
}
}