Spring Boot中如何将一个HTML页面的数据传递到另一个HTML页面
问题根因
你当前的代码核心问题是普通DOM标签的name属性不会被form表单识别为提交参数:浏览器提交表单时,只会收集<input>、<select>、<textarea>这类表单控件的name和对应值携带到请求中,你给<h5>、<li>这类展示标签加th:name是无效的,所以后端Controller无法接收到对应的productName和price参数,自然无法完成数据传递。
修复方案(表单隐藏域实现,最适配你的现有逻辑)
你只需要在每个产品的form内部添加两个隐藏的input控件,用来承载需要提交的产品参数即可,修改后的product.html代码如下:
<div th:each="product:${food}"> <form th:action="@{/payment}" method="get"> <div class="card" style="width: 18rem;"> <!-- 新增隐藏表单域,用来提交产品参数 --> <input type="hidden" th:name="productName" th:value="${product.productName}"> <input type="hidden" th:name="price" th:value="${product.price}"> <div class="card-body"> <h5 class="card-title" th:text="${product.productName}"></h5> <p class="card-text" th:text="${product.description}"></p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item" th:text="${product.productType}"></li> <li class="list-group-item" th:text="${product.price}"></li> <button type="submit" class="btn btn-primary">Buy</button> </ul> </div> </form> </div>
你的现有Controller代码无需修改,参数可以正常接收。之后在payment.html的账单表单中,直接用Thymeleaf取值填充即可:
<!-- 账单表单的产品名输入框示例 --> <input type="text" name="billProductName" th:value="${name}"> <!-- 账单表单的价格输入框示例 --> <input type="text" name="billPrice" th:value="${price}">
其他可实现页面间数据传递的方法
- 路径变量传参:将参数拼接到跳转路径中,form的action修改为
th:action="@{/payment/{productName}/{price}(productName=${product.productName}, price=${product.price})}",Controller对应方法改为用@PathVariable接收参数即可,这种方式适合参数简单、无特殊字符的场景。 - 前端本地存储:点击购买按钮时,用JS将产品信息存入
sessionStorage,跳转到payment页面后再读取存储的值填充到表单,这种方式无需后端参与,纯前端即可实现。 - 会话存储:如果涉及敏感数据不想暴露在请求链路中,可以将产品信息存入
HttpSession,跳转后从会话中读取,不过这个场景不需要这么重的实现。
内容的提问来源于stack exchange,提问作者Kyler Nguyen
相关产品推荐
相关产品推荐

