1、在昨天的項目的pom.XML中添加依賴:內容在前一篇springboot中
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、application.properties中添加thymeleaf的配置信息:
spring.thymeleaf.prefix=classpath:/templates/ //視圖解析器的前綴放在這個文件夾
spring.thymeleaf.suffix=.html //后綴
spring.thymeleaf.mode=HTML5 //模式
spring.thymeleaf.encoding=UTF-8 //編碼格式
spring.thymeleaf.content-type=text/html //文本html語言
spring.thymeleaf.cache=false //不用緩存
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
3、測試:修改控制器
1)@RestController改為@Controller
添加:
@RequestMapping("/demo01")
public String demo01(Model model){
return "index/demo01";
}
2)因為設置了前綴,所以在templates中創建index文件夾,並在中間創建demo01.html。
3)maven update project,打開網址localhost:8080/index/demo01/,顯示頁面,測試成功。
4、thymeleat的使用:
1)替換文本,使用 th:text="${name}" 語句
a、控制器中:
model.addAttribute("name","趙一");
b、demo01中
<div th:text="${name}">我是div1</div>。
刷新頁面,測試成功。
2)替換HTML,使用 th:utext="${name}"語句,HTML中會把控制器中設置的html格式顯示出來。
a、控制器中
model.addAttribute("name","<b><font size='+2' color='red'>趙一</font></b>");
b、demo01中
<div th:utext="${name}">我是div2</div>
刷新頁面,測試成功。
3)循環,使用 th:each="iterator:${Collection}"語句
a、創建Product表,是domain,有produceId、produceName、producePrice三個成員屬性。
b、控制器中:創建商品的集合,將集合添加到model中。
@RequestMapping("/demo01")
public String demo01(Model model){
List<Product>list=new ArrayList<Product>();
for(int i=0;i<10;i++){
Product product=new Product(i,"貓"+i,i+2.00);
list.add(product);
}
model.addAttribute("productList", list);
return "index/demo01";
}
c、demo01中,創建表格:
<table border="1px" class="table">
<thead>
<tr>
<th>商品Id</th>
<th>商品名稱</th>
<th>商品價格</th>
</tr>
</thead>
<tbody>
<tr th:each="iterator:${productList}">
<td th:text="${iterator.produceId}">商品Id</td>
<td th:text="${iterator.produceName}">商品名稱</td>
<td th:text="${iterator.producePrice}">商品價格</td>
</tr>
</tbody>
</table>
刷新頁面,測試成功。
4)循環路徑:比如圖片等等。${}和字符串拼接需“+”號,所以下面有個+號,又因為“/”是特殊符號,所以下面/img/外面添加@{}。
<img th:src="@{/img/}+${iterator.produceImage}"
5)判斷:
th:text="logic?true:false"
a、使用三元運算符
<td th:text="${iterator.producePrice}>6?10.0:1.00">商品價格</td> //大於6,顯示10.0,小於等於6顯示1.00,三元運算符。
b、th:if="logic",當表達式成立顯示這一欄。
<td th:if="${iterator.producePrice}>6">熱銷商品</td>
如果價格>6,顯示熱銷商品,小於6,不顯示這一欄。
6)替換class:外面引用了bootstrap
<lable class="lable lable-sucess">
<td th:class="${iterator.producePrice>6?'lable lable-sucess':'lable lable-danger'}">商品價格</td>
<lable>