Springboot中Thymeleaf简单遍历

本文介绍如何在Spring Boot项目中创建实体类Product,并通过BootController将产品列表传递给视图,使用Thymeleaf模板引擎展示数据。示例代码详细展示了实体类的属性、构造方法和getter/setter方法,以及控制器如何创建产品实例并将其添加到列表中。Thymeleaf模板代码用于遍历产品列表并显示产品名称和价格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,我们建立一个实体类

package com.example.demo.entity;

public class Product {
	
	  private String name;
	  private int price;
	  private int inStock;
	  
	  
	public Product() {
		super();
	}
	public Product(String name, int i, int inStock) {
		super();
		this.name = name;
		this.price = i;
		this.inStock = inStock;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	public int getInStock() {
		return inStock;
	}
	public void setInStock(int inStock) {
		this.inStock = inStock;
	}
	  
	  

}

然后我们在controller里面放值

package com.example.demo.controller;

import java.util.*;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.entity.Product;

@Controller
public class BootController {
          
	         @RequestMapping("/welcome")
	         public String welcome(Map<String,Object> map) {
	        	
	         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";
	         }  
	         
}

因为是初次使用,我们去thymeleaf官网复制实例代码
在这里插入图片描述
在这里插入图片描述

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
            <div th:each="prod : ${prods}">
            <h3 th:text="${prod.name}">Onions</h3>
            <h3 th:text="${prod.price}">2.41</h3>
           
            </div>
</body>
</html>

效果如图所示
在这里插入图片描述

下一篇:Springboot整合外置tomcat及使用jsp开发
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

playboy-jordan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值