springboot整合thymeleaf十分簡單,你不用做任何配置,只需要添加thymeleaf依賴即可直接使用。下面給出例子。
1.創建springboot工程添加依賴
當然也可以直接在工程的pom文件中添加:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.創建測試book類和controller類
public class Book {
private String name;
private int price;
public String getName() {
return name;
}
public Book(String name, int price) {
this.name = name;
this.price = price;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
@Controller
public class BookController {
@GetMapping("/book")
public String getBooks(Model model){
ArrayList<Book> books = new ArrayList<>();
books.add(new Book("a",12));
books.add(new Book("b",13));
books.add(new Book("c",14));
books.add(new Book("d",15));
model.addAttribute("books",books);
return "book";
}
}
3.在templates中創建thymeleaf模板book.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>books</title>
</head>
<body>
<table border="1">
<tr>
<td>name</td>
<td>price</td>
</tr>
<tr th:each="book:${books}">
<td th:text="${book.name}"></td>
<td th:text="${book.price}"></td>
</tr>
</table>
</body>
</html>
4.啓動測試