創建實體類:Produce.java:
package priv.doublechen.Springbootproject.entity;
public class Product {
private String name;
private double price;
private int inStock;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getInStock() {
return inStock;
}
public void setInStock(int inStock) {
this.inStock = inStock;
}
public Product(String name, double price, int inStock) {
super();
this.name = name;
this.price = price;
this.inStock = inStock;
}
}
在控制器中加入:
@RequestMapping("welcome")
public String welcome(Map<String,Object> map){
map.put("abc", "123");//給request域中放入welcome
//給thymeleaf 准備數據
List<Product> prods = new ArrayList<>();
prods.add(new Product("a",100,10));
prods.add(new Product("b",200,20));
prods.add(new Product("c",300,30));
map.put("prods", prods);
return "result";
}
在result.html中加入:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p th:text="${abc}">Welcome to thymeleaf...!</p>
<p>Welcome to thymeleaf...!</p>
<h1>Product list</h1>
<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>IN STOCK</th>
</tr>
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}">yes</td>
</tr>
</table>
</body>
</html>
運行結果:

因為每次springboot項目中的html文件代碼發生修改,總是得重新運行主類,特別麻煩,所以在pom.xml文件中添加依賴:
<!-- 加入以下依賴,代碼做了修改,不用重新運行 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
maven ->update project
每次修改代碼自動編譯,只要刷新頁面就OK了。
