一.前期工作
1.添加依赖
<dependency>
<groupId>org.springframework.boot
</groupId>
<artifactId>spring-boot-starter-thymeleaf
</artifactId>
</dependency>
2.thymeleaf 静态资源配置:src\main\resources\application-dev.yml
#默认
spring
.thymeleaf.prefix=classpath:/templates/
#默认
spring
.thymeleaf.suffix=
.html
#默认
spring
.thymeleaf.mode=HTML5
#默认
spring
.thymeleaf.encoding=UTF-
8
#默认
spring
.thymeleaf.servlet.content-type=text/html
#关闭缓存,即使刷新(上线时改为true)
spring
.thymeleaf.cache=false
二.使用
1.显示静态页面
新建html:src\main\resources\templates\index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HelloThymeleaf
</title>
</head>
<body>
<h1>thymeleaf in spring boot
</h1>
</body>
</html>
控制器:toly1994.com.toly01.controller.ThymeleafController
/**
* 作者:张风捷特烈
* 时间:2018/7/16:16:08
* 邮箱:1981462002@qq.com
* 说明:Thymeleaf模板引擎控制器
*/
@Controller
public class ThymeleafController {
@GetMapping(
"/HelloThymeleaf")
public String
say() {
return "index";
}
}
访问:http://localhost:8080/HelloThymeleaf
2.使用css
配置:src\main\resources\application-dev.yml
mvc:
static-path-pattern: /
static/**
#启用静态文件夹
创建css文件:src\main\resources\static\css\my.css
h1{
color: #00f;
}
引用:src\main\resources\templates\index.html
<link rel="stylesheet" href="../static/css/my.css">
访问:http://localhost:8080/HelloThymeleaf
3.使用js
创建js文件:src\main\resources\static\js\my.js
alert("hello toly!")
引用:src\main\resources\templates\index.html
<script src="../static/js/my.js"></script>
访问:http://localhost:8080/HelloThymeleaf
4.动态替换静态页面数据
使用:src\main\resources\templates\index.html
<body>
<h1 th:text="${replace_text}">thymeleaf in spring boot
</h1>
</body>
控制器:toly1994.com.toly01.controller.ThymeleafController
@GetMapping(
"/useData")
public String
useData(ModelMap map) {
map.addAttribute(
"replace_text",
"张风捷特烈");
return "index";
}
访问:http://localhost:8080/useData
转载于:https://www.cnblogs.com/toly-top/p/9781991.html