《SpringBoot+Vue》Chapter03 整合視圖層

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,相關的配置屬性在ThymeleafProperties類中

  • 默認的模板位置在:classpath:/templates/
  • 默認的模板后綴為:.html
    如果開發(fā)者想修改默認的配置,則可以直接在application.properties中進行配置
# 配置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>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容