文章目錄
-
-
- 一、Freemarker
-
-
-
- 簡介:
- 官網:
- 線上手冊:
-
-
- 二、代碼實戰:
-
-
-
- 1、maven 依賴:
- 2、yml 檔案配置:
- 3、建立Freemarker模闆檔案
- 4、建立測試Controller
- 5、啟動項目,進行測試
-
-
-
一、Freemarker
簡介:
FreeMarker 是一款 模闆引擎: 即一種基于模闆和要改變的資料, 并用來生成輸出文本(HTML網頁,電子郵件,配置檔案,源代碼等)的通用工具。 它不是面向最終使用者的,而是一個Java類庫,是一款程式員可以嵌入他們所開發産品的元件。
模闆編寫為FreeMarker Template Language (FTL)。它是簡單的,專用的語言, 不是 像PHP那樣成熟的程式設計語言。 那就意味着要準備資料在真實程式設計語言中來顯示,比如資料庫查詢和業務運算, 之後模闆顯示已經準備好的資料。在模闆中,你可以專注于如何展現資料, 而在模闆之外可以專注于要展示什麼資料。
官網:
https://freemarker.apache.org/">https://freemarker.apache.org/
線上手冊:
模闆常用文法
,可以參考這個中文線上手冊,這裡不再贅述
http://freemarker.foofun.cn/"> http://freemarker.foofun.cn/
二、代碼實戰:
1、maven 依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2、yml 檔案配置:
spring:
application:
name: freemarker
freemarker:
# 禁用模闆緩存
cache: false
# 編碼格式
charset: UTF-8
# freemarker模闆字尾 預設是 .ftl
suffix: .html
# 是否為此技術啟用MVC視圖分辨率。
enabled: true
# Content-Type值
content-type: text/html
# #模闆加載路徑 按需配置 ,預設路徑是 classpath:/templates/
template-loader-path: classpath:/templates/
3、建立Freemarker模闆檔案
由于在配置中配置了模闆字尾為 .html(預設為 .ftl),是以這裡建立一個 index.html 檔案
檔案内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
Hello ${content}
</body>
</html>
4、建立測試Controller
/**
* created with IntelliJ IDEA.
* author: fxbin
* date: 2018/10/21
* time: 4:15
* version: 1.0
* description:
*/
@Controller
public class FreemarkerController {
@RequestMapping("/index")
public String index(Model model){
model.addAttribute("content", "Freemarker");
return "index";
}
}
5、啟動項目,進行測試
浏覽器通路 : http://localhost:8080/index
可以看到 模闆中寫的
${content}
已經被代碼中的 Freemarker 取代了

代碼位址
— end —