freemarker学习记录

package example;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
* 测试
* @author wesley
*/
public class TestServlet extends HttpServlet {

    private Configuration cfg;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //初始化FreeMarker配置,创建Configuration实例
        cfg = new Configuration();
        cfg.setDefaultEncoding("UTF-8");
        //设置FreeMarker的模版文件位置
        cfg.setServletContextForTemplateLoading(getServletContext(), "templates");
        //建立数据模型
        Map root = new HashMap();
        //放入对应数据
        root.put("title", "使用Freemarker生成静态页面实例!");
        root.put("content", "FreeMarker是一个模板引擎,一个基于模板生成文本输出的通用工具,使用纯Java编写FreeMarker被设计用来生成HTML Web页面,特别是基于MVC模式的应用程序虽然FreeMarker具有一些编程的能力,但通常由Java程序准备要显示的数据,由FreeMarker生成页面,通过模板显示准备的数据(如下图)");
        root.put("author", "小仇");
        root.put("answer", 43);
        
        Map latestMap = new HashMap();
        latestMap.put("url", "www.baidu.com");
        latestMap.put("name", "green mouse");
        root.put("latestMap", latestMap);
        
        root.put("indexOf", new IndexOfMethod());
        
        List> list = new ArrayList>();
        
        Map map11 = new HashMap();
        map11.put("name", "qiuyujiao1");
        map11.put("age", 21);
        list.add(map11);
        
        Map map22 = new HashMap();
        map22.put("name", "qiuyujiao2");
        map22.put("age", 22);
        list.add(map22);
        
        Map map33 = new HashMap();
        map33.put("name", "qiuyujiao3");
        map33.put("age", 23);
        list.add(map33);
        
        Map map44 = new HashMap();
        map44.put("name", "qiuyujiao4");
        map44.put("age", 24);
        list.add(map44);
        
        root.put("listtest", list);
        //建立模型结束---
        //获得模版文件
        Template template = cfg.getTemplate("test.ftl"); 
        //开始准备生成输出,使用模版文件的charset作为本页面的charset
        response.setContentType("text/html;charset=" + template.getEncoding());
        PrintWriter printWriter = response.getWriter(); 
        try {
            //合并数据模型和模版,并将结果输出到printWriter中(把数据放到了printWriter里面跟生成动态页面没关系)
            template.process(root, printWriter);
            File newHtml = getHtmlFile();
            doWrite(template, newHtml.getPath(), root);   //生成静态页面
            printWriter.print(""+newHtml.getName()+"");
            
//            String path = dirName+"/"+newHtml.getName();
//            HttpSession session = request.getSession(true);
//            session.setAttribute("path", path);
          
        } catch (Exception ex) {
            //Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex);
            throw new ServletException("处理Template模版中出现错误", ex);
        }
    }
    /**
     * 得到已经生成的文件,以便根据已经生成的文件获取文件名字和文件路径
     * @return  已经生成的文件
     */
    private File getHtmlFile(){
    	 long htmlName = Calendar.getInstance().getTimeInMillis();
         Date date = new Date(htmlName);
         SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
         String dirName = f.format(date);
         //存放生成后的静态页面的目录 eg:2008-9-9
         String saveDirectory = getServletContext().getRealPath("/") + dirName + "//";
         File dir = new File(saveDirectory);
         //如果目录不存在,则创建目录
         if (!dir.exists()) {
             dir.mkdir();
         }
         //生成静态文件
         File newHtml = new File(dir + "/" + htmlName + ".html");
         return newHtml;
    	
    }
    
    
    

    /**
     * 生成静态文件
     * @param template : 模版
     * @param path : 静态页面路径
     * @param root : 数据模型
     */
    private void doWrite(Template template, String path, Map root) { 
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(path));
            template.setEncoding(cfg.getDefaultEncoding());
            template.process(root, bw);
            bw.flush();
        } catch (TemplateException ex) {
            Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                bw.close();
            } catch (IOException ex) {
                Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
   
}


主要就是两个文件一个附件方法变量类

1,TestServlet.java 如下:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(freemarker学习记录)