You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Thymeleaf中向Controller提交列表数据?

嘿,别慌!新手刚接触Thymeleaf遇到问题太正常啦,我来帮你捋捋~

首先先把你给出的Controller代码格式化补全(看起来你最后一行代码截断了,我猜应该是把testBean放到model里对吧?):

@Controller
public class TestController {
    @GetMapping(value = "/")
    public String testget(Map<String, Object> model) {
        TestBean bean = new TestBean();
        List<Person> list = new ArrayList<>();
        for (int index = 1; index < 5; index++) {
            Person p = new Person();
            p.setId(index);
            p.setName("name" + index);
            list.add(p);
        }
        model.put("allList", "nothing");
        bean.setList(list);
        model.put("testBean", bean); // 补全你截断的代码部分
        return "index"; // 假设返回的视图是index.html
    }
}

假设你是想在Thymeleaf页面里渲染testBean里的Person列表,那对应的页面代码可以这么写:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Test Page</title>
</head>
<body>
    <h2>Person List from TestBean</h2>
    <ul>
        <!-- 用th:each遍历testBean里的list集合 -->
        <li th:each="person : ${testBean.list}">
            ID: <span th:text="${person.id}"></span>, Name: <span th:text="${person.name}"></span>
        </li>
    </ul>

    <!-- 输出allList的值 -->
    <p>allList的内容: <span th:text="${allList}"></span></p>
</body>
</html>

给你划几个新手必注意的关键点:

  • 一定要在html标签上加上Thymeleaf的命名空间xmlns:th="http://www.thymeleaf.org",不然Thymeleaf的属性会失效。
  • 必须给TestBean和Person类写对应的getter方法!比如TestBean要有getList(),Person要有getId()和getName(),Thymeleaf是通过调用getter来获取属性值的,没写的话页面上会拿不到数据哦。
  • Spring Boot默认会去src/main/resources/templates目录找视图文件,所以你的html文件要放在这个文件夹里,不然会找不到页面。

如果你的问题不是这个,可以把具体需求或者报错信息补充一下,我再帮你调整~

内容的提问来源于stack exchange,提问作者beike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:32:56