当前位置: 代码迷 >> 综合 >> 模板生成html文件
  详细解决方案

模板生成html文件

热度:93   发布时间:2024-03-08 09:24:17.0

1.Velocity生成html

package com.geely.omserver.utils;import org.apache.commons.io.IOUtils;import org.apache.commons.lang3.CharEncoding;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;import java.io.*;
import java.util.Map;public class  VelocityUtil {private static VelocityEngine engine = new VelocityEngine();static {engine.setProperty(Velocity.RESOURCE_LOADER, "class");engine.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");engine.init();}public static void mergeTemplate(String templatePath, Map<String, Object> context, File outputFile) {BufferedWriter bw = null;try {Template t = engine.getTemplate(templatePath, CharEncoding.UTF_8);VelocityContext vc = new VelocityContext();for (Map.Entry<String, Object> ent : context.entrySet()) {vc.put(ent.getKey(), ent.getValue());}try(OutputStream os = new FileOutputStream(outputFile);){bw = new BufferedWriter(new OutputStreamWriter(os, CharEncoding.UTF_8));t.merge(vc, bw);bw.flush();}catch (Exception e) {e.printStackTrace();}} catch (Exception e) {throw new RuntimeException(e);} finally {IOUtils.closeQuietly(bw);}}}

 

  相关解决方案