SpringBoot集成freemarker和thymeleaf模板

时间:2024-09-08 00:05:32

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

 package com.leecx.controller;

 import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
@RequestMapping("/ftl")
public class FreemarkerController { @RequestMapping("/freemaker")
public String index(ModelMap modelMap){
modelMap.put("name", "duanml");
return "freemarker/index";
} @RequestMapping("/center")
public String center(ModelMap modelMap){
modelMap.put("name", "duanml");
return "freemarker/center/center";
}
}

如:ThymeleafController.java

 package com.leecx.controller;

 import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
@RequestMapping("/th")
public class ThymeleafController { @RequestMapping("/thymeleaf")
public String index(ModelMap modelMap){
modelMap.put("name", "duanml");
return "thymeleaf/index";
} @RequestMapping("/center")
public String center(ModelMap modelMap){
modelMap.put("name", "duanml");
return "thymeleaf/center/center";
}
}

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

SpringBoot集成freemarker和thymeleaf模板

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