FreeMarkerUtil

来源:互联网 发布:云计算代表企业 编辑:程序博客网 时间:2024/06/03 18:15

package com.css.common.util;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

/**
 * 模板工具类   <br/>
 *
 * @author 何青
 */
public class FreeMarkerUtil {
 
 /**
  * @param templatePath 模块文件的路径
  * @param templateName 模板文件名称
  * @param root 数据模型根对象
  * @param templateEncoding 模板文件的编码方式
  */
 public static String analysisTemplate(String templatePath,String templateName,String templateEncoding,Map<String,Object> root){
  Writer out = null;
  try {
   Configuration config=new Configuration();
   File file=new File(templatePath);
   //设置要解析的模板所在的目录,并加载模板文件
   config.setDirectoryForTemplateLoading(file);
   //设置包装器,并将对象包装为数据模型
   config.setObjectWrapper(new DefaultObjectWrapper());
   
   //获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致
   Template template=config.getTemplate(templateName,templateEncoding);
   //合并数据模型与模板
   out = new StringWriter();
      template.process(root, out);
      return out.toString();
  } catch (Exception e) {
   e.printStackTrace();
  }finally
  {
   try {
    out.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  return "";
 }
}