package com.taover.util; import java.io.StringWriter; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; public class UtilTemplate { /** * 通过velocity引擎渲染模板文件,模板所在类路径 * @param templateClassPath * @param data * @return */ public static String renderTemplateClass(String templateClassPath, Map data) throws Exception{ //初始化 VelocityEngine ve = new VelocityEngine(); Properties p = new Properties(); p.put("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.SimpleLog4JLogSystem"); p.put("runtime.log.logsystem.log4j.category", "velocity"); p.put("runtime.log.logsystem.log4j.logger", "velocity"); p.put(VelocityEngine.INPUT_ENCODING, "UTF-8"); p.put(VelocityEngine.OUTPUT_ENCODING, "UTF-8"); p.put(VelocityEngine.ENCODING_DEFAULT, "UTF-8"); p.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); ve.init(p); //取得VelocityContext对象 VelocityContext context = new VelocityContext(); //向context中放入要在模板中用到的数据对象 if(data != null){ Set keySet = data.keySet(); Iterator iter = keySet.iterator(); while(iter.hasNext()){ String key = iter.next(); context.put(key, data.get(key)); } } //选择要用到的模板 if( !ve.resourceExists(templateClassPath) ){ return null; } Template template; StringWriter sw = new StringWriter(); template = ve.getTemplate(templateClassPath, "UTF-8"); //合并输出 template.merge( context, sw); return sw.toString(); } }