一、什么是Thymeleaf ?
Thymeleaf 是 Web 和独立环境的现代服务器端 Java 模板引擎,其实就是一个的模板引擎,它可以完全替代 JSP ,能够处理HTML,XML,JavaScript,CSS 甚至纯文本。
前端交给我们的页面,是html页面。如果是我们以前开发,我们需要把他们转成jsp页面,jsp好处就是当我们查出一些数据转发到JSP页面以后,我们可以用jsp轻松实现数据的显示,及交互等。
jsp支持非常强大的功能,包括能写Java代码,但是呢,我们现在的这种情况,SpringBoot这个项目首先是以jar的方式,不是war,像第二,我们用的还是嵌入式的Tomcat,所以呢,他现在默认是不支持jsp的。
二、引入Thymeleaf
引入依赖
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
代码测试
1、编写一个TestController
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping("index")
public String index(Model model){
model.addAttribute("msg", "hello thymeleaf");
return "test";
}
}
2、我们要使用thymeleaf,需要在html文件中导入命名空间的约束,方便提示。
我们可以去官方文档的#3中看一下命名空间拿来过来:
xmlns:th="http://www.thymeleaf.org"
3、前端页面
编写一个test.html放在templates目录下即可
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>测试页面</title>
</head>
<body>
<!--th:text就是将div中的内容设置为它指定的值-->
<div th:text="${msg}"></div>
</body>
</html>
三、Thymeleaf 语法
要学习语法,还是参考官网文档最为准确,
Thymeleaf 官网:https://www.thymeleaf.org/
<span th:text="${student.name}"></span>
字符串拼接:<h2 th:text="'姓名:'+${student.name}"></h2>
三元表达式:<input th:value="${age gt 30 ? '中年':'年轻'}"/>
gt:great than(大于)
ge:great equal(大于等于)
eq:equal(等于)
lt:less than(小于)
le:less equal(小于等于)
ne:not equal(不等于)
取list中的数据
java:
List<Book> books = new ArrayList<Book>();
for (int i = 0; i < 10; i++) {
Book b = new Book("book"+i, 100f, "http://www.wendaoxueyuan.com/images/"+i+".jpg");
books.add(b);
}
map.addAttribute("books",books);
html
<table border="1px" cellspacing="0px" cellspadding="0px" width="100%">
<tr>
<td>编号</td><td>书名</td><td>书价格</td><td>图片地址</td>
</tr>
<tr th:each="book:${books}">
<td>编号</td>
<td th:text="${book.bookName}">书名</td>
<td th:text="${book.bookPrice}">书价格</td>
<td th:text="${book.bookUrl}">图片地址</td>
</tr>
</table>