0、创建SpringBoot的web项目
1、引入FreeMarker依赖包
<!--引入FreeMarker依赖包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2、配置SpringBoot的配置文件
SpringBoot项目启动会默认扫描resources目录下的application.properties文件或者applicatiion.yml文件(idea会默认创建该文件的空文件;eclipse不会自动创建,手动创建即可,还需手动创建:static文件夹、templates文件夹)
注意:SpringBoot项目启动会默认扫描resources目录下application.properties文件或者applicatiion.yml文件、static文件夹、templates文件夹
推荐一个yml与properties互转的在线工具:yml与properties在线互转
如果是properties文件,配置如下内容
# 允许请求重写
spring.freemarker.allow-request-override=false
# 缓存
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
# 字符集
spring.freemarker.charset=utf-8
spring.freemarker.content-type=text/html
# 前缀
#spring.freemarker.prefix=
# 后缀
spring.freemarker.suffix=.ftl
# template模板加载路径
spring.freemarker.template-loader-path=classpath:/templates/
此处使用yml文件,所以在yml文件配置如下内容
spring:
freemarker:
allow-request-override: false
cache: true
charset: utf-8
check-template-location: true
content-type: text/html
suffix: .ftl
template-loader-path: classpath:/templates/
3、创建Controller,写一个方法用于请求访问,同时给前端传值
@Controller
public class FtlController {
@RequestMapping(value = "toftl")
public String toFtl(Map<String,Object> map){
map.put("ftl","这是FreeMark模板,后端给前端传值");
return "index";
}
}
4、在templates文件夹中创建一个ftl文件
5、启动项目访问