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();
            }
        }
    }
}

 

转载于:https://www.cnblogs.com/yang1018/p/9086783.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值