freemarker

package cn.gov.bjkepu.www.util.method;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;


import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
/**
 * Freemarker创建静态HTML类
 * @author zxj
 *
 */
public class FreemarkerMethod {
    /**
     * @author zxj
     * @param templateDirPath 模版存放路径 例如template
     * @param templateFileName 模版文件名 例如index.flt
     * @param root Map<String,Object> 例如root.put("newList",newList)
     * @param outputPath HTML文件输出地址
     * @throws IOException 
     */
    public static void createHtml(HttpServletRequest request,String templateDirPath,String templateFileName,Map<String,Object> root, String outputPath) throws Exception {
        Writer out = null;
        try {
            
            ServletContext application = request.getSession().getServletContext();
          
            Configuration config = new Configuration();
            
            //加载模版路径
            config.setDirectoryForTemplateLoading(new File(application.getRealPath("/")+templateDirPath));
            
            //设置编码
            config.setEncoding(Locale.CHINA, "UTF-8");
            
            //设置包装器,并将对象包装为数据模型  
            config.setObjectWrapper(new DefaultObjectWrapper());
            
            //设置异常处理器,屏蔽生成文件中的错误信息
            config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
            
            //加载模版文件
            Template template = config.getTemplate(templateFileName);           
            
            //定义模板输出
            out = new OutputStreamWriter(new FileOutputStream(application.getRealPath("/")+outputPath),"UTF-8");
            
            //basePath项目根路径
            String path = request.getContextPath();    
            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
            root.put("basePath", basePath);
            
            //模板渲染
            template.process(root, out);
            
            out.flush();
 
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(out!=null ){
                 out.flush();   
                 out.close();
            }
        }
    }
}

 

posted @ 2018-05-25 09:35  石洋  阅读(161)  评论(0)    收藏  举报