import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
public class HelloVelocity {
public static void main(String[] args) throws Exception {
// 初始化并取得Velocity引擎
VelocityEngine ve = new VelocityEngine();
ve.init();
// 取得velocity的模版,注意:test.vm放到你的项目根目录,不会src目录
Template t = ve.getTemplate("test.vm","UTF-8");
// 取得velocity的上下文context
VelocityContext context = new VelocityContext();
// 把数据填入上下文
context.put("name", "javaboy2012");
context.put("date", (new Date()).toString());
//将java类实例,填入上下文,在模板中使用
Cal c=new Cal();
context.put("caltool", c);
News news1=new News();
news1.setAuthor("author1");
news1.setId(1);
news1.setTitle("title1");
News news2=new News();
news2.setAuthor("author2");
news2.setId(2);
news2.setTitle("title2");
News news3=new News();
news3.setAuthor("author3");
news3.setId(3);
news3.setTitle("title3");
List<News> items = new java.util.ArrayList<News>();
items.add(news1);
items.add(news2);
items.add(news3);
//把list数据放入上下文,在模板中使用
context.put("items", items);
List temp = new ArrayList();
temp.add("1");
temp.add("2");
context.put("list", temp);
// 输出流
StringWriter writer = new StringWriter();
// 转换输出
t.merge(context, writer);
System.out.println(writer.toString());
}
}
public class Cal {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public static int add(int a,int b)
{
return a+b;
}
}
public class News {
private int id;
private String title;
private String author;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
<html>
<title>Hello Velocity</title>
<body>
Welcome $name to Javayou.com!
today is $date.
#foreach( $product in $list )
<li>$product</li>
#end
$caltool.add(1,2)
#foreach ($one in $items)
<li> 第 $velocityCount 个 <a href="${one.getId()}" title="${one.getTitle()}">${one.getAuthor()}</a></li>
#end
</body>
</html>