關於Thymeleaf的優點,我只說一條:它就是html頁面啊,直接可以用瀏覽器打開。受夠了JSP的同學可以嘗試一下。
1.在pom.xml文件中添加依賴:
<!--<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>
spring-boot-starter-thymeleaf下面已經包括了spring-boot-starter-web,所以可以把spring-boot-starter-web的依賴去掉。
2.配置屬性。其實完全可以使用不用配置,但是Spring Boot官方文檔建議在開發時將緩存關閉,那就在application.properties文件中加入下面這行吧:
spring.thymeleaf.cache=false
3.編寫Controller類。
package com.yws710.springboot.demo1.controller; import com.yws710.springboot.demo1.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/user") public class UserController { @Autowired UserService userService; @RequestMapping("/list2") public String userList2(Model model) throws Exception { model.addAttribute("hello","Hello, Spring Boot!"); model.addAttribute("userList", userService.userList()); return "/user/list2"; } }
4.創建Thymeleaf模板文件。在classpath:resources下創建一個名為templates的文件夾,在templates的子文件夾user中創建一個名為list2.html的文件。
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" /> <title>用戶列表</title> <link href="/css/main.css" rel="stylesheet" /> </head> <body> <h1 th:text="${hello}">Hello, Spring Boot!</h1> <table> <tr> <th>ID</th> <th>姓名</th> <th>生日</th> <th>薪資</th> </tr> <tr th:each="user : ${userList}"> <td th:text="${user.id}">0</td> <td th:text="${user.name}">zhansan</td> <td th:text="${user.birthday}">1988-06-01</td> <td th:text="${user.salary}">12345</td> </tr> </table> <select> <option th:each="user:${userList}" th:value="${user.id}" th:text="${user.name}">我是默認值</option> </select> </body> </html>
需要注意的是,模板文件中的所有標簽都需要閉合哦。meta標簽需要這么寫:<meta charset="UTF-8" />或者<meta charset="UTF-8"></meta>。但是,難免有疏忽的時候,那怎么辦?使用3版本吧。只需要在pom.xml文件中增加如下代碼:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- set thymeleaf version --> <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version> </properties>
這樣就不用擔心單標簽關閉的問題了,更符合書寫習慣。
5.啟動項目,查看運行結果:
作為對比,直接在瀏覽器中打開list2.html看看會怎樣?
很遺憾,樣式文件沒加載到。模板文件中是這樣寫的:
<link href="/css/main.css" rel="stylesheet" />
但是樣式文件是在classes/static/css中呢。淡淡的憂傷。
使用如下方式即可很好地解決上述問題。
<link href="../../static/css/main.css" th:href="@{/css/main.css}" rel="stylesheet" />