import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
public class Test {
public void getSql(Map<String,Object> map,String fileName) {
try {
Velocity.init();
//获取上下文
VelocityContext context = new VelocityContext();
Template template = null;
try {
//获取模板引擎
VelocityEngine ve = new VelocityEngine();
//模板文件所在的路径
String path = "";
//path = "tomcatPath" + "/webapps/xxx/WEB-INF/classes/xxx/vm";
path = "F:/";
//设置参数
ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,path);
//初始化模板
ve.init();
//获取模板
template = ve.getTemplate(fileName);
//把数据填入上下文
if(null !=map){
Set<String> set = map.keySet();
for(String label : set){
context.put(label,map.get(label));
}
}
} catch (ResourceNotFoundException e2) {
System.out.println("cannot find template " + fileName);
} catch (ParseErrorException e) {
System.out.println("Syntax error in template : " + e);
}
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
System.out));
if (template != null)
template.merge(context, writer);
writer.flush();
writer.close();
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
String fileName = "select.vm";
Map<String,Object> map = new HashMap<String, Object>();
map.put("from", 1);
map.put("to", 3);
new Test().getSql(map,fileName);
}
}
velocity的应用
最新推荐文章于 2024-06-13 15:25:38 发布