FreeMarker 简介
Apache FreeMarker是一个基于Java语言开发的模板引擎,用于根据模板和不断变化的数据生成文本输出(例如:HTML网页,电子邮件,配置文件,源代码等)。FreeMarker模板使用FTL模板语言编写,这是一种简单的专用语言,在模板中,你专注于如何显示数据,在模板之外,你专注于呈现什么样的数据。。
版本依赖
- JDK 8
- SpringBoot 2.3.0
- FreeMarker 2.3.30
整合FreeMarker
maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
application.yml
server:
port: 8080
spring:
# 配置Freemarker
freemarker:
# 模板文件后缀名
suffix: .ftl
# 文档类型
content-type: text/html
# 页面编码格式
charset: UTF-8
# 页面缓存
cache: false
# 请求环境路径
request-context-attribute: request
# 模板文件路径
template-loader-path:
- classpath:/templates
templates 目录下添加 hello.ftl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Freemarker</title>
</script>
</head>
<body>
<h2>Hello ${name}!</h2>
</body>
</html>
添加 HelloController 类
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("name", "freemaker");
return "hello";
}
}
参考
https://freemarker.apache.org/
https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#boot-features-jsp-limitations
https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html