码迷,mamicode.com
首页 > Web开发 > 详细

用Freemarker生成Html页面

时间:2015-08-08 13:35:02      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

  例子:MakeFileManager.java

 

package example;

import freemarker.template.Configuration;
import java.text.SimpleDateFormat;
import java.io.File;
import freemarker.template.DefaultObjectWrapper;
import java.util.Map;
import java.util.HashMap;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import freemarker.template.TemplateException;
import java.io.IOException;
import freemarker.template.Template;

public class MakeFileManager {
    public String make(Book book, BookFtl bookFtl) {
        Configuration cfg = new Configuration();//配制

        String realPath = bookFtl.getRealPath();
        String templatePath = realPath + "/WEB-INF/templates/book";
        String cDateStr = "book/" +
                          new SimpleDateFormat("yyyyMMdd").format(new java.util.
                Date());
        String filePostfix = ".html";
        String path = realPath + "/" + cDateStr;
        String fileTimeName = new SimpleDateFormat("yyyyMMddhhmmss").format(new
                java.util.Date());
        String returnFileName = cDateStr + "/" + fileTimeName + filePostfix;
        String fileName = "";
        File bookDir = new File(path);
        if (bookDir.exists()) {
            fileName = path + "/" + fileTimeName + filePostfix;
        } else {
            bookDir.mkdirs();
            fileName = path + "/" + fileTimeName + filePostfix;
        }
        try {
            //设置freemarker的参数
            cfg.setNumberFormat("0.##########");//生成html文件时web.xml配制无效
            //cfg.setEncoding();
            cfg.setDirectoryForTemplateLoading(new File(templatePath));
            cfg.setObjectWrapper(new DefaultObjectWrapper());
            Template bookTemplate = cfg.getTemplate(bookFtl.getTemplateName());//模板对象
            Map root = new HashMap();
            root.put("book", book);
            root.put("book2",book);
            Writer out = new OutputStreamWriter(new FileOutputStream(fileName));
            try {
                bookTemplate.process(root, out);
            } catch (TemplateException e) {
                e.printStackTrace();
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return returnFileName;
    }
}

用Freemarker生成Html页面

标签:

原文地址:http://www.cnblogs.com/Crow00/p/4712984.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!