FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。
Freemarker中文手册: FreeMarker 中文官方参考手册
目录
一、初始化Springboot项目
二、引入依赖文件
三、编写配置文件
四、编写Controller类
五、编写模板文件
六、预览效果
一、初始化Springboot项目
二、引入依赖文件
<!-- 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>
三、编写配置文件
application.yml
# freemarker模板引擎
spring:
freemarker:
allow-request-override: true
allow-session-override: true
# 是否开始缓存
cache: false
check-template-location: true
# 默认编码格式
charset: UTF-8
content-type: text/html;
expose-request-attributes: true
expose-session-attributes: true
expose-spring-macro-helpers: true
# 模板放置位置
template-loader-path: classpath:/templates/
# 文件目录前缀
prefix:
# 文件后缀
suffix: .ftl
request-context-attribute: request
settings:
template_update_delay: 0
url_escaping_charset: UTF-8
locale: UTF-8
# 日期时间格式化
datetime_format: yyyy-MM-dd HH:mm:ss
# 日期格式化
date_format: yyyy-MM-dd
# 时间格式化
time_format: HH:mm:ss
template_exception_handler: html_debug
# 数字格式化,无小数点
number_format: '0.#'
# 设置freemarker标签 0,1,2 0=自动识别,默认1
tag_syntax: 'auto_detect'
四、编写Controller类
IndexController.java
package com.csdn.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.HashMap;
import java.util.Map;
@Controller
public class IndexController {
@GetMapping("/index")
public String index(ModelMap model) {
Map<String, Object> info = new HashMap<>();
info.put("name", "Roc-xb");
info.put("age", "25");
info.put("date", "2021年12月10日19:48:01");
model.put("info", info);
return "index";
}
}
五、编写模板文件
index.ftl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>freemaker测试页面</title>
</head>
<body>
<div>${info.name}</div>
<div>${info.age}</div>
<div>${info.date}</div>
</body>
</html>