freemarker整合
pom.xml文件添加依赖
<!-- 引入freemarker模板依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
项目结构和application.yml配置如下
application.yml
spring:
# freemarker静态资源配置
freemarker:
# 设定ftl文件路径
template-loader-path: classpath:/templates
# 关闭缓存,及时刷新,上线生产环境需要改为true
cache: false
charset: UTF-8
check-template-location: true
content-type: text/html
expose-request-attributes: true
expose-session-attributes: true
request-context-attribute: request
suffix: .ftl
FreemarkerController.java
package com.xiangty.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.xiangty.pojo.Resource;
@Controller
@RequestMapping(value = "ftl")
public class FreemarkerController {
@Autowired
private Resource resource;
@RequestMapping("/index")
public String index(ModelMap map) {
map.addAttribute("resource", resource);
return "freemarker/index";
}
@RequestMapping("/center")
public String center() {
return "freemarker/center/center";
}
}
templates/freemarker/index.ftl
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>FreeMarker模板引擎</title>
</head>
<body>
FreeMarker模板引擎
<h1>${resource.name}</h1>
<h1>${resource.website}</h1>
<h1>${resource.language}</h1>
</body>
</html>
templates/freemarker/center/center.ftl
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>FreeMarker模板引擎</title>
</head>
<body>
FreeMarker模板引擎
<h1>center page</h1>
</body>
</html>
启动项目,测试如下:
thymeleaf整合
项目结构如下
引入依赖
<!-- 引入 thymeleaf 模板依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
application.yml配置
spring:
# thymeleaf静态资源配置
thymeleaf:
#关闭缓存,及时刷新
cache: false
prefix: classpath:/templates/
suffix: .html
mode: HTML5
encoding: UTF-8
servlet:
content-type: text/html
templates/thymeleaf/index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>Thymeleaf模板引擎</title>
</head>
<body>
Thymeleaf模板引擎
<h1 th:text="${name}">hello world~~~~~~~</h1>
</body>
</html>
ThymeleafContorller.java
package com.xiangty.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "th")
public class ThymeleafController {
@RequestMapping("/index")
public String index(ModelMap map) {
map.addAttribute("name", "thymeleaf测试Name");
return "thymeleaf/index";
}
@RequestMapping("/center")
public String center() {
return "thymeleaf/center/center";
}
}
测试效果如下:
以上是freemarker、thymeleaf的基本用法,示例代码可以查看Spring Boot开发常用技术博客目录内的文章。