FreeMarker 之快速入門Demo

weixin_33785972發表於2018-07-05
  • 開發環境
    • freemaker版本2.3.23
    • Eclipse Mars.2

建立maven的jar工程

在eclipse中new 一個maven project,填入如下的資訊,建立工程,工程起名為freemakerdemo

8032945-0a4eb98138151b55.png

匯入依賴

在pom.xml中引入如下的依賴

     <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.23</version>
        </dependency>

建立模板檔案

在resource目錄下,建立test.ftl檔案

8032945-bd594e25057b7a51.png

test.ftl檔案中寫入如下的內容

<html>
<head>
    <meta charset="utf-8">
    <title>Freemarker入門小DEMO </title>
</head>
<body>
<#--我只是一個註釋,我不會有任何輸出  -->
${name},你好。${message}
</body>
</html>

新建測試類生成html檔案

建立如下圖的測試類


8032945-5c2aa28d17f37376.png

測試類中的程式碼如下

package com.thc.test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import freemarker.template.Configuration;
import freemarker.template.Template;
@SuppressWarnings("all")
public class Test01 {
    public static void main(String[] args) throws Exception {
        // 1.設定配置類
        Configuration configuration = new Configuration(Configuration.getVersion());
        //2. 設定模板所在的目錄
        configuration.setDirectoryForTemplateLoading(
                new File("D:/develop/eclipse_workspace/eclipsePinyougou/freemakerdemo/src/main/resources/"));
        //3.設定字符集
        configuration.setDefaultEncoding("utf-8");
        //4.載入模板
        Template template = configuration.getTemplate("test.ftl");
        //5.建立資料模型
        HashMap map = new HashMap();
        map.put("name", "周杰倫");
        map.put("message", "我是你的老歌迷了");
        //6.建立Writer物件
        FileWriter writer = new FileWriter(new File("D:/freemaker/test.html"));
        //7.輸出資料模型到檔案中
        template.process(map, writer);
        //8.關閉Writer物件
        writer.close(); 
    }
}

執行該main方法後,在D:\freemaker目錄下,生成了html檔案

8032945-811f719ef1a10e0c.png

開啟頁面後顯示如下的內容

8032945-e4beb7cdecbb7b49.png

可以看到在java程式碼中,map中put的name和message替代了模板檔案中的內容.