首页 > 代码库 > FreeMarker模板使用

FreeMarker模板使用

package com.piccapp.util;import java.io.IOException;import java.io.StringWriter;import java.util.Map;import net.sf.json.JSONObject;import com.sinosoft.base.Log.Log;import freemarker.template.Configuration;import freemarker.template.Template;import freemarker.template.TemplateException;/** * 组织freeMarker工具 * 开始时间:2014-10-27 by ligang * 上线时间: */public class FreeMarkerUtil {    private Configuration cfg = null;    private static FreeMarkerUtil freeMarkerUtil= null;    private static Template  getInstance(String filename){        Template tmp = null;        if(freeMarkerUtil==null){            freeMarkerUtil=new FreeMarkerUtil();        }        try {            tmp = freeMarkerUtil.cfg.getTemplate(filename);            tmp.setEncoding("UTF-8");        } catch (IOException e) {            Log.err("freeMarker", "找不到模板");            e.printStackTrace();        }        return tmp;    }    private FreeMarkerUtil() {           cfg = new Configuration();           try {           cfg.setClassForTemplateLoading(this.getClass(),"/freeMarkerModel/");           } catch (Exception e) {               Log.err("freeMarker", "配置错误!");           }          }    public static String modelToString(String modelname,Map param){        Template tmplTemplate = FreeMarkerUtil.getInstance(modelname);        StringWriter sw = new StringWriter();        String xmlTextString = "";        try {            tmplTemplate.process(param, sw);            xmlTextString=sw.toString();            sw.close();        } catch (TemplateException e) {            Log.err("freeMarker", "生成XML失败");            e.printStackTrace();        } catch (IOException e) {            Log.err("freeMarker", "写入失败");            e.printStackTrace();        }        return xmlTextString;    }}

process方法可以使json或者Map

FreeMarker模板使用