1. 程式人生 > >freeMarker匯出html檔案

freeMarker匯出html檔案

1.什麼是freemarker?

FreeMarker 是一款 模板引擎: 即一種基於模板和要改變的資料, 並用來生成輸出文字(HTML網頁,電子郵件,配置檔案,原始碼等)的通用工具。 它不是面向終端使用者的,而是一個Java類庫,是一款程式設計師可以嵌入他們所開發產品的元件。

模板編寫為FreeMarker Template Language (FTL)。它是簡單的,專用的語言, 不是 像PHP那樣成熟的程式語言。 那就意味著要準備資料在真實程式語言中來顯示,比如資料庫查詢和業務運算, 之後模板顯示已經準備好的資料。在模板中,你可以專注於如何展現資料, 而在模板之外可以專注於要展示什麼資料。

這種方式通常被稱為 MVC (模型 檢視 控制器) 模式,對於動態網頁來說,是一種特別流行的模式。 它幫助從開發人員(Java 程式設計師)中分離出網頁設計師(HTML設計師)。設計師無需面對模板中的複雜邏輯, 在沒有程式設計師來修改或重新編譯程式碼時,也可以修改頁面的樣式。

作用

FreeMarker最初的設計,是被用來在MVC模式的Web開發框架中生成HTML頁面的,它沒有被繫結到 Servlet或HTML或任意Web相關的東西上。它也可以用於非Web應用環境中。

根據提供的資料和建立好的模板,去自動的建立html靜態頁面.

2. 實戰

pom.xml

      <!--FreeMarker需要新增的Maven依賴:-->
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency> <!--FreeMarker需要新增的Maven依賴:-->

test.ftl

<html>
<head
>
<title>Welcome!</title> </head> <body> <h1>Hello ${w}!</h1> <#list articleVoList as article> <p><a href="/article/${article.id}">${article.title}</a></p> </#list> </body> </html>

java控制器

package com.majker.modules.api;

import com.majker.modules.blog.entity.vo.ArticleQueryVo;
import com.majker.modules.blog.entity.vo.ArticleVo;
import com.majker.modules.blog.service.ArticleService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/****************************************************
 *
 *  FreeMarker匯出html
 * @author zhouzf
 * @date 2018-09-25 21:47
 * @version 1.0
 **************************************************/
@Controller
@RequestMapping("test")
public class FreeMarkerController {
    @Resource
    Configuration cfg;

    @Autowired
    private ArticleService articleService;

    @GetMapping("main")
    public String main(Model model, HttpServletRequest request, HttpServletResponse response) {
        cfg.setDefaultEncoding("UTF-8");
        cfg.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/docTemplate");
        String w = "Welcome FreeMarker!";
        Map root = new HashMap();


        try {
            ArticleQueryVo queryVo=new ArticleQueryVo();
            root.put("w", w);
            List<ArticleVo> articleVoList=articleService.findArticle(queryVo);
            root.put("articleVoList", articleVoList);
            response.setContentType( "application/html; charset=UTF-8");
            response.setHeader("Content-Disposition","Attachment;filename= " + new String(("index.html").getBytes("UTF-8"),"UTF-8"));
            freeMarkerContent(root,response.getWriter());
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
//        model.addAttribute("w", "Welcome FreeMarker!");
        return "test";
    }

    private void freeMarkerContent(Map<String, Object> root,Writer wt) {
        try {

            Template temp = cfg.getTemplate("test.ftl");
            //以classpath下面的static目錄作為靜態頁面的儲存目錄,同時命名生成的靜態html檔名稱
//            String path = this.getClass().getResource("/").toURI().getPath() + "static/test.html";
//            Writer file = new FileWriter(new File(path.substring(path.indexOf("/"))));
            temp.process(root, wt);
//            file.flush();
//            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }


}

連結: http://freemarker.foofun.cn/index.html.