Spring-boot集成freemarker入門(mén)|實(shí)踐

Spring-boot集成freemarker入門(mén)|實(shí)踐

介紹

官方介紹 https://freemarker.apache.org/

百度百科:https://baike.baidu.com/item/freemarker/9489366?fr=aladdin

關(guān)于介紹本文就不重復(fù)敘述了

下面直接開(kāi)始實(shí)踐做瞪!

Freemarker + Springboot Maven配置基礎(chǔ)工程

創(chuàng)建一個(gè)maven項(xiàng)目

spring-boot項(xiàng)目中添加依賴

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring‐boot‐starter‐freemarker</artifactId>
        </dependency>
    </dependencies>

在resource目錄下添加配置文件

server:
  port: 8088 # 服務(wù)端口
spring:
  application:
    name: test-freemarker
  freemarker:
    cache: false #關(guān)閉模板緩存,方便測(cè)試
    settings:
        template_update_delay: 0 #檢查模板更新延遲時(shí)間柴灯,設(shè)置為0表示立即檢查偏窝,如果時(shí)間大于0會(huì)有緩存不方便進(jìn)行模板測(cè)試

創(chuàng)建數(shù)據(jù)模型類(lèi)

package com.dsdj.test.freemarker.model;

import lombok.Data;
import lombok.ToString;

import java.util.Date;
import java.util.List;

/**
 * model
 *
 * @author dsdj
 * @version 1.0
 * @className Student
 * @date 2019/2/12 9:09
 **/
@Data
@ToString
public class Student {
    private String name;//姓名
    private int age;//年齡
    private Date birthday;//生日
    private Float money;//錢(qián)包
    private List<Student> friends;//朋友列表
    private Student bestFriend;//最好的朋友
}

這里使用了lombok需要引入下面的依賴

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.16</version>
</dependency>

創(chuàng)建模板

在 src/main/resources下創(chuàng)建templates曼尊,此目錄為freemarker的默認(rèn)模板存放目錄。

在templates下創(chuàng)建模板文件demo.ftl.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf‐8">
    <title>Hello World!</title>
</head>
<body>
Hello ${name}!
</body>
</html>

模板中的${name}最終會(huì)被freemarker替換成具體的數(shù)據(jù)阅虫。

創(chuàng)建controller

創(chuàng)建Controller類(lèi)粘都,向Map中添加name,最后返回模板文件甥温。

添加依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

創(chuàng)建啟動(dòng)類(lèi)

package com.dsdj.test.freemarker;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * spring boot 啟動(dòng)類(lèi)
 *
 * @author dsdj
 * @version 1.0
 * @className FreemarkerTestApplication
 * @date 2019/2/12 9:41
 **/
@SpringBootApplication
public class FreemarkerTestApplication {
    public static void main(String[] args) {
        SpringApplication.run(FreemarkerTestApplication.class,args);
    }
}

啟動(dòng)測(cè)試

1549936254247.png

FreeMarker基礎(chǔ)

關(guān)于freemarket的知識(shí)點(diǎn)锻煌,主要是掌握一起下知識(shí)

  • 總體結(jié)構(gòu)

  • 指令(幾個(gè)核心指令)

  • 表達(dá)式

  • 插值

讀者可以參考下面的教程

http://freemarker.foofun.cn/dgui_template_overallstructure.html

這個(gè)教程是翻譯自官方的文檔×蓿可以快速瀏覽一遍炼幔,不懂再去查閱。

在掌握了基礎(chǔ)的語(yǔ)法之后史简,下面進(jìn)行靜態(tài)化實(shí)踐乃秀。

freemarker靜態(tài)化實(shí)踐

使用模板文件靜態(tài)化

創(chuàng)建測(cè)試類(lèi)

package com.dsdj.test.freemarkert;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author dsdj
 * @version 1.0
 * @className TestFreemarker
 * @date 2019/2/12 10:30
 **/

public class TestFreemarker {
    @Test
    public void testGenerateHtml() throws IOException, TemplateException, URISyntaxException {
        // 創(chuàng)建配置類(lèi)
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 設(shè)置模板路徑 toURI()防止路徑出現(xiàn)空格
        String classpath = this.getClass().getResource("/").toURI().getPath();
        configuration.setDirectoryForTemplateLoading(new File(classpath+"/templates/"));
        // 設(shè)置字符集
        configuration.setDefaultEncoding("utf-8");
        // 加載模板
        Template template = configuration.getTemplate("demo1.ftl");
        // 數(shù)據(jù)模型
        Map<String,Object> map = new HashMap<>();
        map.put("name", "靜態(tài)化測(cè)試");
        // 靜態(tài)化
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
        // 打印靜態(tài)化內(nèi)容
        System.out.println(content);
        InputStream inputStream = IOUtils.toInputStream(content);
        // 輸出文件
        FileOutputStream fileOutputStream = new FileOutputStream(new File("demo1.html"));
        int copy = IOUtils.copy(inputStream, fileOutputStream);

    }
}

測(cè)試結(jié)果

1549951894520.png

使用模板字符串靜態(tài)化

測(cè)試方法

@Test
public void testGenerateHtmlByString() throws IOException, TemplateException {
    // 創(chuàng)建配置類(lèi)
    Configuration configuration = new Configuration(Configuration.getVersion());
    // 測(cè)試模板內(nèi)容
    String templateString="" +
            "<html>\n" +
            " <head></head>\n" +
            " <body>\n" +
            " 名稱(chēng):${name}\n" +
            " </body>\n" +
            "</html>";
    // 模板加載器
    StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
    stringTemplateLoader.putTemplate("template",templateString);
    configuration.setTemplateLoader(stringTemplateLoader);
    // 得到模板
    Template template = configuration.getTemplate("template","utf-8");
    // 數(shù)據(jù)模型
    Map<String,Object> map = new HashMap<>();
    map.put("name","使用模板字符串靜態(tài)化");
    // 靜態(tài)化
    String content = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
    // 打印靜態(tài)化內(nèi)容
    System.out.println(content);
    InputStream inputStream = IOUtils.toInputStream(content);
    // 輸出文件
    FileOutputStream fileOutputStream = new FileOutputStream(new File("demo1.html"));
    int copy = IOUtils.copy(inputStream, fileOutputStream);
}
1549952513189.png

以上就是freemarker的基本使用,但看到這里我們肯定有很多疑問(wèn)圆兵。下面進(jìn)行總結(jié)

總結(jié)

為什么可以直接直接跳轉(zhuǎn)跺讯?

模板靜態(tài)化如何在場(chǎng)景下使用?

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末殉农,一起剝皮案震驚了整個(gè)濱河市刀脏,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌超凳,老刑警劉巖愈污,帶你破解...
    沈念sama閱讀 219,427評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件耀态,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡暂雹,警方通過(guò)查閱死者的電腦和手機(jī)首装,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)杭跪,“玉大人仙逻,你說(shuō)我怎么就攤上這事〗颍” “怎么了系奉?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,747評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)姑廉。 經(jīng)常有香客問(wèn)我缺亮,道長(zhǎng),這世上最難降的妖魔是什么桥言? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,939評(píng)論 1 295
  • 正文 為了忘掉前任瞬内,我火速辦了婚禮,結(jié)果婚禮上限书,老公的妹妹穿的比我還像新娘。我一直安慰自己章咧,他們只是感情好倦西,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,955評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著赁严,像睡著了一般扰柠。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上疼约,一...
    開(kāi)封第一講書(shū)人閱讀 51,737評(píng)論 1 305
  • 那天卤档,我揣著相機(jī)與錄音,去河邊找鬼程剥。 笑死劝枣,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的织鲸。 我是一名探鬼主播舔腾,決...
    沈念sama閱讀 40,448評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼搂擦!你這毒婦竟也來(lái)了稳诚?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,352評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤瀑踢,失蹤者是張志新(化名)和其女友劉穎扳还,沒(méi)想到半個(gè)月后才避,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,834評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡氨距,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,992評(píng)論 3 338
  • 正文 我和宋清朗相戀三年桑逝,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片衔蹲。...
    茶點(diǎn)故事閱讀 40,133評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡肢娘,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出舆驶,到底是詐尸還是另有隱情橱健,我是刑警寧澤,帶...
    沈念sama閱讀 35,815評(píng)論 5 346
  • 正文 年R本政府宣布沙廉,位于F島的核電站拘荡,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏撬陵。R本人自食惡果不足惜珊皿,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,477評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望巨税。 院中可真熱鬧蟋定,春花似錦、人聲如沸草添。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,022評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)远寸。三九已至抄淑,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間驰后,已是汗流浹背肆资。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,147評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留灶芝,地道東北人郑原。 一個(gè)月前我還...
    沈念sama閱讀 48,398評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像夜涕,于是被迫代替她去往敵國(guó)和親颤专。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,077評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容