package com.yuelun.wochengz.util; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Locale; import java.util.Map; import javax.servlet.http.HttpServlet; import org.apache.struts.action.ActionServlet; import freemarker.template.Configuration; import freemarker.template.Template; @SuppressWarnings("unchecked") public class FreeMarkerFactory extends HttpServlet{ /** * * @param ftl 模版名称 * @param htmlName 生成的THML名称 * @param path html存放路径 * @param fileName 模版存放文件夹 * @param root 数据模型 * @return */ public static boolean init(String ftl,String htmlName,String path,String fileName,Map root,ActionServlet servlet){ boolean flag = true; Configuration config = new Configuration(); //加载模版 config.setServletContextForTemplateLoading(servlet.getServletContext(), "/"+fileName); //设置编码 config.setEncoding(Locale.getDefault(), "GBK"); try { //指定模版 Template template = config.getTemplate(ftl); template.setEncoding("GBK"); File io = new File(path); if(!io.exists()){ io.mkdirs(); } //输出THML Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path,htmlName)),"GBK")); //解析文件并输出 template.process(root, out); } catch (Exception e) { flag = false; e.printStackTrace(); } return flag; } }