import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
public class HtmlUtil {
/**
* 将数据与模版板进行合并
* @param writer 输出流
* @param map 数据
* @param vmName 模板文件名
* @param encoding 编码格式
* @throws Exception
*/
public static void generate(Writer writer, Map<String, Object> map,
String encoding,String vmRelPath,String vmName) throws Exception {
Properties p = new Properties();
p.setProperty("file.resource.loader.path", vmRelPath);
VelocityEngine engin = new VelocityEngine();
engin.init(p);
Template template = engin.getTemplate(vmName, encoding);
Context context = new VelocityContext();
for(Iterator<String> i = map.keySet().iterator(); i.hasNext(); ) {
String key = i.next();
context.put(key, map.get(key));
}
template.merge(context, writer);
}
/**
* 合并数据,生成文件
* @param file 文件
* @param map 数据
* @param encoding 编码
* @throws Exception
*/
public static void merge(File file, Map<String, Object> map, String encoding,String vmPath,String vmName) throws Exception {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding));
generate(bw, map, encoding,vmPath,vmName);
} finally {
bw.close();
}
}
public static void main(String[] args) throws Exception{
//生成静态文件位置
File file = new File("D:/web/", "test.html");
Map<String, Object> map = new HashMap<String, Object>();
//模版文件所需要的数据
map.put("special", "test");
//模版文件
merge(file, map, "UTF-8","D:/special/","special.vm");
}
}
注:
上述代码通过velocity文件生成静态html文件