SpringBoot整合Thymeleaf

Thymeleaf是一种用于Web和独立环境的现代服务器端的Java模板引擎。它能够处理HTML,XML,JavaScript,CSS甚至纯文本。

现在记录一下在Springboot项目中如何来整合Thymeleaf模板引擎。

1.新建一个springboot web项目,并添加下面依赖。

2.新建实体book类

@Data
public class Book {

	private Integer id;
	private String name;
	private String price;

}

3.新建controller类

@Controller
public class UserController {

	@RequestMapping("/index")
	public String bookInfo(Model model) {
		List<Book> books = new ArrayList<>(0);

		for (int i = 0; i < 10; i++) {
			Book book = new Book();
			book.setId(i);
			book.setName("书名" + i);
			book.setPrice(10 + i);
			books.add(book);
		}
		model.addAttribute("books", books);
		return "bookIndex";
	}

}

4.在resources的templates目录下新建一个html

注意:在整合thymeleaf模板引擎的时候,添加  xmlns:th="http://www.thymeleaf.org"  命名空间

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>书本信息</title>
</head>
<body>
<table border="2">


  <tr>
    <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.price}"></td>
  </tr>

</table>
</body>
</html>

5.启动springboot项目

6.通过浏览器访问接口

至此,Springboot整合Thymeleaf模板引擎的一个简单案例就分享完了,本案例中只是简单使用了Thymeleaf模板引擎的each迭代用法,更多的指令可以到官网查看文档:https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#use-in-forms

现在项目中常用的模板引擎除了Thymeleaf之外还有Freemarker,下一篇就是记录springboot项目整合Freemarker模板引擎:https://blog.csdn.net/qq_43655835/article/details/102897254

原文地址:https://www.cnblogs.com/wgty/p/12810490.html