Freemarker的使用和小Demo

FreeMarker是一款模板引擎: 即一種基於模板和要改變的數據, 並用來生成輸出文本(HTML網頁、電子郵件、配置文件、源代碼等)的通用工具。 它不是面向最終用戶的,而是一個Java類庫,是一款程序員可以嵌入他們所開發產品的組件。

小Demo
1.導入依賴
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.23</version>
        </dependency>
2.創建一個模板

文件後綴名爲ftl,下面爲舉例模板並有相應的方法
說明:
標記開頭都是<#
取值是用${}取值的

<html>
<head>
    <meta charset="utf-8">
    <title>Freemarker 入門小 DEMO </title>
</head>
<body>
    <#--我只是一個註釋,我不會有任何輸出 -->
	<#-- 取值通過${}取 -->
    ${name},你好。${message}
    
    <#--定義變量-->
    <#assign age=18>
    我今年${age}歲
    
    <#--導入別的模板-->
    <#include "title.ftl">
    
    <#--if else語句-->
    <#if false>
        我是if
        <#else>
        我是else
    </#if>

    ----家裏動物喫什麼---
    <#--遍歷集合   listAnial是傳的集合名-->
    <#list listAnial as dongwu>
        ${dongwu_index+1}: 動物:${dongwu.name}喫:${dongwu.eat}
    </#list>
    
    <#--內置函數  用來獲取總記錄數-->
    總共:${listAnial?size}條記錄

    <#--將json字符串轉成json對象-->
    <#--定義一個json字符串-->
    <#assign text="{'class':'五方橋基地','name':'郭子軒'}">
    <#assign data=text?eval>
    班級:${data.class}  姓名:${data.name}
    </body>
</html>
3.寫代碼
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {
    public static void main(String[] args) throws IOException, TemplateException {
        //1.創建Configuration 對象
        Configuration configuration = new Configuration(Configuration.getVersion());
        //2. 配置模板文件地址(也就是你模板存放的位置)
        configuration.setDirectoryForTemplateLoading(new File(".\\src\\main\\resources\\template"));
        //3.設置字符集  準備工作 setting--File Encodings 設置成UTF-8
        configuration.setDefaultEncoding("utf-8");
        //4.加載模板(模板名)
        Template template = configuration.getTemplate("demo.ftl");
        //5.創建數據模型
        Map map=new HashMap();    //回傳的數據

        map.put("name", "學員");
        map.put("message", "歡迎來優就業學習!");
        //模擬數據庫讀的數據集合
        Map map1=new HashMap();
        map1.put("name", "狗");
        map1.put("eat", "骨頭!");
        Map map2=new HashMap();
        map2.put("name", "魚");
        map2.put("eat", "蝦米!");
        List listAnial = new ArrayList();
        listAnial.add(map1);
        listAnial.add(map2);

        map.put("listAnial",listAnial);
        //6.輸出靜態頁面的地址
        FileWriter out = new FileWriter(new File(".\\src\\main\\resources\\demo.html"));
        //7.調用模板進行渲染 這裏很關鍵! 是給頁面回傳參數,這裏傳的是Map集合
        template.process(map, out);
        System.out.println("生成成功");
        //關閉輸出流
        out.close();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章