FreeMarker 是一款模板引擎: 即一種基於模板和要改變的數據, 並用來生成輸出文本( HTML 網頁、電子郵件、配置文件、源代碼等)的通用工具。
它不是面向最終用戶的,而是一個 Java 類庫,是一款程序員可以嵌入他們所開發產品的組件。
FreeMarker 是一個很值得去學習的模版引擎。它是基於模板文件生成其他文本的通用工具。
本文主要介紹在 SpringBoot 中如何整合 FreeMarker,一起來看看吧!!!
1、引入 Freemarker 依賴
<!-- Freemarker 依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- web 依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
通過 org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,我們可以看到 FreeMarker 的自動化配置,在這個類的構造方法中,注入了 FreeMarkerProperties:
@ConfigurationProperties(prefix = "spring.freemarker")
public class FreeMarkerProperties extends AbstractTemplateViewResolverProperties {
public static final String DEFAULT_TEMPLATE_LOADER_PATH = "classpath:/templates/";
public static final String DEFAULT_PREFIX = "";
public static final String DEFAULT_SUFFIX = ".ftl";
/**
* Well-known FreeMarker keys which are passed to FreeMarker's Configuration.
*/
private Map<String, String> settings = new HashMap<>();
}
FreeMarkerProperties 中則配置了 Freemarker 的基本信息,例如模板位置在 classpath:/templates/ ,再例如模板後綴爲 .ftl,那麼這些配置我們以後都可以在 application.yml 中進行修改。
2、在 application.yml 中進行配置 Freemarker
當然,SpingBoot 已經幫我們自動配置好了關於 Freemarker 的一系列配置,但是我們仍可以對其進行個性化配置
spring:
freemarker:
# 是否開啓緩存
cache: false
# 模板文件編碼
charset: UTF-8
# 是否檢查模板位置
check-template-location: true
# Content-Type的值
content-type: text/html
# 模板文件後綴
suffix: .ftl
# 模板文件位置
template-loader-path: classpath:/templates/
3、編寫 Controller
@Controller
public class IndexController {
/**
* 請求 index 頁面
* @return
*/
@GetMapping("index")
public ModelAndView index() {
ModelAndView mav = new ModelAndView("index");
mav.addObject("title", "首頁");
List<UserInfo> list = new ArrayList<>();
UserInfo user = null;
for (int i = 0; i < 10; i++) {
user = new UserInfo();
user.setId(i + 1);
user.setNickName("user" + i);
user.setSignature("SpringBoot真香,+" + (i + 1));
list.add(user);
}
mav.addObject("users", list);
return mav;
}
}
4、創建 index.ftl 模板文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>${title}</title>
</head>
<body>
<table border="1">
<tr>
<td>用戶編號</td>
<td>用戶暱稱</td>
<td>個性簽名</td>
</tr>
<#list listas item>
<td>${item.id}</td>
<td>${item.nickName}</td>
<td>${item.signature}</td>
</#list>
</table>
</body>
</html>
5、展示效果
總結
與 Thymeleaf 一樣,在 SpringBoot 中對 Freemarker 做了一系列的自動化配置,真正做到了開箱即用,非常易於開發。
如您在閱讀中發現不足,歡迎留言!!!