Thymeleaf简介:
Thymeleaf 是新一代 Java 模板引擎,它类似于 Velocity、FreeMarker 等传统 Java 模板引擎,但是与传统 Java 模板引擎不同的是,Thymeleaf 支持 HTML 原型。
它既可以让前端工程师在浏览器中直接打开查看样式,也可以让后端工程师结合真实数据查看显示效果,同时,SpringBoot 提供了 Thymeleaf 自动化配置解决方案,因此在 SpringBoot 中使用 Thymeleaf 非常方便。
事实上, Thymeleaf 除了展示基本的 HTML ,进行页面渲染之外,也可以作为一个 HTML 片段进行渲染,例如我们在做邮件发送时,可以使用 Thymeleaf 作为邮件发送模板。
另外,由于 Thymeleaf 模板后缀为 .html,可以直接被浏览器打开,因此,预览时非常方便。
下面来了解一下thymeleaf具体的应用
1.创建springboot工程,引入thymeleaf模板引擎
2.连按两次shift搜索ThymeleafAutoConfiguration
@ConditionalOnClass({TemplateMode.class, SpringTemplateEngine.class})
上面的代码表示你要有thymeleaf依赖才能实现下面的功能,而我么已经在pom.xml中添加了thymeleaf依赖:
查看注解
@EnableConfigurationProperties({ThymeleafProperties.class})
按住ctrl点击ThymeleafProperties,可以发现一些约定的规则:
首先thymeleaf默认编码是UTF-8,需要放在templates包下,后缀名是.html。
在类名前还有@ConfigurationProperties( prefix = "spring.thymeleaf" )
这个是安全属性注入
到目前位置thymeleaf配置内容和约定已经都看到了,接下来我们就来创建一个具体的例子
3.创建实体类book
package org.javaboy.thymeleaf.bean;
public class Book {
private Integer id;
private String name;
private String author;
private Double price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
'}';
}
}
4.创建控制类
package org.javaboy.thymeleaf.controller;
import org.javaboy.thymeleaf.bean.Book;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.ArrayList;
import java.util.List;
@Controller
public class BookController {
@GetMapping("/book")
public String book(Model model) {
List<Book> bookList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Book book = new Book();
book.setId(i);
book.setName("三国演义:" + i);
book.setAuthor("罗贯中:" + i);
book.setPrice(30.0);
bookList.add(book);
}
model.addAttribute("books",bookList);
return "book";
}
}
5.创建book.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table>
<tr>
<td>图书编号</td>
<td>图书名称</td>
<td>图书作者</td>
<td>图书价格</td>
</tr>
<tr th:each="book :${books}">
<td th:text="${book.id}"></td>
<td th:text="${book.name}"></td>
<td th:text="${book.author}"></td>
<td th:text="${book.price}"></td>
</tr>
</table>
</body>
</html>
因为thymeleaf模板引擎后缀名就是html,直接在templates包下创建就可以了。
在 Thymeleaf 中,通过 th:each 指令来遍历一个集合,数据的展示通过 th:text 指令来实现
6.启动项目
访问:http://localhost:8080/book