Thymeleaf
Thymeleaf是新一代Java模板引擎践叠,與傳統(tǒng)Java模板引擎不同的是言缤,Thymeleaf支持HTML原型,可以讓前端工程師直接在瀏覽器中打開查看樣式禁灼,也可以讓后端工程師結(jié)合真實數(shù)據(jù)查看顯示效果管挟。SpringBoot提供了Thymeleaf自動化配置解決方案。
創(chuàng)建工程弄捕,添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
配置Thymeleaf
SpringBoot為Thymeleaf提供了自動化配置類ThymeleafAutoConfiguration,相關(guān)的配置屬性在ThymeleafProperties類中
- 默認(rèn)的模板位置在:classpath:/templates/
- 默認(rèn)的模板后綴為:.html
如果開發(fā)者想修改默認(rèn)的配置僻孝,則可以直接在application.properties中進(jìn)行配置
# 配置Thymeleaf
# 開啟模板緩存
spring.thymeleaf.cache=true
# 檢查模板是否存在
spring.thymeleaf.check-template=true
# 模板文件編碼
spring.thymeleaf.encoding=utf-8
# 模板文件位置
spring.thymeleaf.prefix=classpath:/templates/
# content-type配置
spring.thymeleaf.servlet.content-type=text/html
# 模板文件后綴
spring.thymeleaf.suffix=.html
配置控制器
創(chuàng)建Book實體類,Controller中返回ModelAndView
@Controller
public class BookController {
@GetMapping("/books")
public ModelAndView books() {
ArrayList<Book> books = new ArrayList<Book>();
for (int i = 0; i < 3; i++) {
Book book = new Book(i, "book" + i, "author" + i);
books.add(book);
}
ModelAndView mv = new ModelAndView();
mv.addObject("books", books);
mv.setViewName("books");
return mv;
}
}
創(chuàng)建視圖
在resources目錄下的templates目錄中創(chuàng)建books.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1">
<tr>
<td>圖書編號</td>
<td>圖書名</td>
<td>圖書作者</td>
</tr>
<tr th:each="book:${books}">
<td th:text="${book.id}"/>
<td th:text="${book.name}"/>
<td th:text="${book.author}"/>
</tr>
</table>
</body>
</html>