- 改文章項目文件結構圖如下:
步驟一:創建工程、添加依賴
<dependencies>
<!-- thymeleaf相關依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- web項目依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
步驟二:配置thymeleaf,部分常見配置如下:
#是否開啓緩存,開發時可設置爲false,默認爲true
spring.thymeleaf.cache=false
#是否檢查模板是否存在,默認爲true
spring.thymeleaf.check-template=true
#是否檢查模板位置是否存在,默認爲true
spring.thymeleaf.check-template-location=true
#模板文件編碼
spring.thymeleaf.encoding=UTF-8
#模板文件位置
spring.thymeleaf.prefix=classpath:/templates/
#Content-Type配置
spring.thymeleaf.servlet.content-type=text/html
#模板文件後綴
spring.thymeleaf.suffix=.html
步驟三:配置控制器
- 首先配置實體類Book.java
package cn.aju.study;
public class Book {
private Integer id;
private String name;
private String author;
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;
}
}
然後再BookController 中返回ModelAndView,代碼如下:
package cn.aju.study;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.List;
@Controller
public class BookController {
@GetMapping("/books")
public ModelAndView books() {
List<Book> books = new ArrayList<Book>();
Book b1 = new Book();
b1.setId(1);
b1.setAuthor("羅貫中");
b1.setName("三國演義");
books.add(b1);
Book b2 = new Book();
b2.setId(2);
b2.setAuthor("曹雪芹");
b2.setName("紅樓夢");
books.add(b2);
ModelAndView mv = new ModelAndView();
mv.addObject("books", books);
//設置視圖顯示位置與模板名稱
mv.setViewName("test/demo");
return mv;
}
}
第四步:創建視圖:demo.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>books</title>
</head>
<body>
<div>找到了test目錄下的demo頁面</div>
<div>遍歷ModelANdView中的books數據</div>
<table border="1">
<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.author}"></td>
</tr>
</table>
</body>
</html>
- xmlns:th:表示導入Thymeleaf的名稱空間,這樣在Idea中使用Thymeleaf語法將不會報錯
步驟五:我們運行之後的顯示結果如下圖所示