我有一个带有下一个代码的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”的所有复选框的值属性。您需要将所有这些复选框的值属性更新为wd.getId()而不是wd.getType(),这样您就可以获得已检查项目的ID。
最后,要指定初始检查/未检查状态,请使用th:checked="${wd.getType()}"
而不是th:value(后者需要保存上面提到的id。)