SpringBoot集成freemarker和thymeleaf模板

1、在MAVEN工程POM.XML中引入依赖架包

<!-- 引入 freemarker 模板依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- 引入 thymeleaf 模板依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2、在属性系统配置文件中application.properties 加入相关配置

############################################################
#
# freemarker 静态资源配置
#
############################################################
#设定ftl文件路径
spring.freemarker.template-loader-path=classpath:/templates
# 关闭缓存, 即时刷新, 上线生产环境需要改为true
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl


############################################################
#
# thymeleaf 静态资源配置
#
############################################################
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
# 关闭缓存, 即时刷新, 上线生产环境需要改为true
spring.thymeleaf.cache=false

3、具体的Controller实体类中需要注解

如:FreemarkerController.java

 1 package com.leecx.controller;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.ui.ModelMap;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 
 7 @Controller
 8 @RequestMapping("/ftl")
 9 public class FreemarkerController {
10 
11     @RequestMapping("/freemaker")
12     public String index(ModelMap modelMap){
13         modelMap.put("name", "duanml");
14         return "freemarker/index";
15     }
16     
17     @RequestMapping("/center")
18     public String center(ModelMap modelMap){
19         modelMap.put("name", "duanml");
20         return "freemarker/center/center";
21     }
22 }

如:ThymeleafController.java

 1 package com.leecx.controller;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.ui.ModelMap;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 
 7 @Controller
 8 @RequestMapping("/th")
 9 public class ThymeleafController {
10 
11     @RequestMapping("/thymeleaf")
12     public String index(ModelMap modelMap){
13         modelMap.put("name", "duanml");
14         return "thymeleaf/index";
15     }
16     
17     @RequestMapping("/center")
18     public String center(ModelMap modelMap){
19         modelMap.put("name", "duanml");
20         return "thymeleaf/center/center";
21     }
22 }

4、在项目的工程中静态资源建立如下的层级关系:

注意freemarker和thymeleaf  两者的静态页面的后缀是不一样的。

原文地址:https://www.cnblogs.com/yinfengjiujian/p/8797393.html