创建实体类: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了。