第一种写法新建一个HTML文件,内容为:
<html>
<title>Hello Velocity</title>
<body>
Welcome $name to Javayou.com!
today is $date.
</body>
</html>
然后通过Java代码读取HTML文件,并解析参数,输出结果
第二种写法,使用场景多为HTML页面内容存在数据库,通过SQL获取后为String格式,然后解析
Java代码如下:
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
public class HelloWorld {
public static void main(String args[]){
/**
* name to Javayou.com!
*today is $date.
*/
Map map = new HashMap();
map.put("name", "sdmjhca");
map.put("date", (new Date()).toString());
new HelloWorld().replaceByVelocity(map);
StringBuffer temp = new StringBuffer();
temp.append("<html>\n ");
temp.append("<title>Hello Velocity</title>\n ");
temp.append("<body>\n ");
temp.append("Welcome $name to Javayou.com! \n ");
temp.append("today is $date.\n ");
temp.append("</body> \n ");
temp.append("</html> \n ");
new HelloWorld().replaceByVelocity(map,temp.toString());
}
public void replaceByVelocity(Map map){
VelocityEngine vi = new VelocityEngine();
vi.init();
Template template = vi.getTemplate("heloWorld.html", "UTF-8");
VelocityContext vc = new VelocityContext();
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()){
Map.Entry entry = (Entry) iter.next();
String key = entry.getKey().toString();
String value = entry.getValue().toString();
vc.put(key, value);
}
StringWriter writer = new StringWriter();
//System.out.println("---------"+template.getData().toString());
template.merge(vc, writer);
System.out.println(writer.toString());
}
public void replaceByVelocity(Map map,String template){
VelocityEngine vi = new VelocityEngine();
vi.init();
VelocityContext vc = new VelocityContext();
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()){
Map.Entry entry = (Entry) iter.next();
String key = entry.getKey().toString();
String value = entry.getValue().toString();
vc.put(key, value);
}
StringWriter writer = new StringWriter();
vi.evaluate(vc, writer, "", template);
//writer.write(s);
//template.merge(vc, writer);
//System.out.println(writer.toString());
}
}