gpt4 book ai didi

java - 如何使用 Thymeleaf 和 spring 将对象或数组从 html 页面发送到 POST 方法

转载 作者:太空宇宙 更新时间:2023-11-04 10:12:33 24 4
gpt4 key购买 nike

我有一个 html 页面,其中包含以下代码:

<div class="w3-container w3-light-grey">
<div class="w3-container w3-grey">

<form th:action="@{'/wordprocess/' + ${descriptionId}}" method="post">
<table class="w3-table-all w3-card-4">
<tr>
<th>Id</th>
<th>Word</th>
<th>Type</th>
<th></th>
</tr>
<tr th:each="wd : ${wordslist}">
<td th:text="${wd.getId()}">Jill</td>
<td th:text="${wd.getWord()}">Jill</td>
<td th:if="${wd.getType() == 0}" th:text="word">Jill</td>
<td th:if="${wd.getType() == 1}" th:text="skill">Jill</td>
<td>
<p>
<input class="w3-check" type="checkbox" name="type" th:value="${wd.getType()}">
<label>Skill</label>
</p>
</td>
</tr>
</table>
<input class="w3-button w3-black" type="submit" value="Save"/>
</form>
</div>
</div>

在\p\ block 中,我使用复选框来初始化对象类型。字段“type”可以获取两个整数值:0 或 1。

我希望能够在复选框中指定此类型的值(1 - 选中,0 - 未选中)并在 POST 方法中获取此数组:

@RequestMapping(value = "/wordprocess/{descriptionId}", method = RequestMethod.POST)
public String save(
@PathVariable long descriptionId,
@RequestParam(value = "type", required = false) int[] type
){
System.out.println(descriptionId);
System.out.println(type[0]);
return "index";
}

但是在 save() 方法中,我的“type”变量中有一个空值。

如何在 POST 方法中正确发送一组复选框值?

最佳答案

第一条规则,使用复选框/单选按钮,您不会将未选中的项目返回到服务器,而只会将选中的项目返回到服务器。如果您将 HttpServletRequest 请求添加到 save() 方法的参数列表(它将由 Spring 自动填充),您应该能够调用 request.getParameterValues("type")用于名称为“type”的所有复选框的值属性。您需要将所有这些复选框的 value 属性更新为 wd.getId() 而不是 wd.getType(),这样您就可以获得选中项目的 ID。

最后,要指定初始选中/未选中状态,请使用 th:checked="${wd.getType()}"而不是 th:value (后者需要保存上面提到的 id。)

关于java - 如何使用 Thymeleaf 和 spring 将对象或数组从 html 页面发送到 POST 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52141727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com