1.在模块下导入依赖坐标
<!-- Spring Boot 对结果视图 Freemarker 集成 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.编写配置文件
这里是在nacos下配置
spring:
freemarker:
enabled: true
cache: false #关闭模板缓存,方便测试
settings:
template_update_delay: 0
suffix: .ftl #页面模板后缀名
charset: UTF-8
template-loader-path: classpath:/templates/ #页面模板位置(默认为 classpath:/templates/)
resources:
add-mappings: false #关闭项目中的静态资源映射(static、resources文件夹下的资源)
3.在resources文件目录下新建一个目录templates,为什么叫templates,因为我在nacos配置文件中路径写的就叫这个,根据需求改即可
<body>标签内的${name}是占位符,到时候可以去FreemarkerController类中给它赋上一些值
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World!</title>
</head>
<body>
Hello ${name}!
</body>
</html>
4.新建一个FreemarkerController类
@Controller
public class FreemarkerController {
@GetMapping("/testfreemarker")
public ModelAndView test(){
ModelAndView modelAndView = new ModelAndView();
//设置模型数据
modelAndView.addObject("name","小明");
//根据视图名称.ftl找到视图模板
modelAndView.setViewName("test");
return modelAndView;
}
}
5.启动程序,前往查看,运行正常