java - 如何将 ArrayList 生成的复选框中的值发布到 Thymeleaf 和 Spring 中具有表单的另一个对象 ArrayList?
问题描述
我有一个表单,它接受用户的几个输入来创建一个对象,其中一个输入是一组复选框。
复选框是从Model
带有名为“GrapeList”ArrayList
的对象生成的,但我无法弄清楚如何将它们添加到提交表单时创建的对象中。Grape
我的表格如下所示:
<form class="col-12" action="#" th:action="@{/admin}" th:object="${Wine}" method="post">
<div class="row">
<div class="col-1">
<label for="nameInput">Name: </label>
</div>
<div class="col-11">
<input class="w-100" id="nameInput" type="text" th:field="*{name}">
</div>
</div>
<div class="col-1">
<label for="descriptionInput">Description: </label>
</div>
<div class="col-11">
<textarea class="w-100" id="descriptionInput" type="text" th:field="*{description}"></textarea>
</div>
</div>
====================PROBLEM=======================
<div class="row" th:each="grape: ${GrapeList}">
<div class="col">
<label th:for="'grape' + ${grape.name}" th:text="${grape.name}"></label>
</div>
<div class="col">
<input type="checkbox" th:id="'grape' + ${grape.name}" th:value="${grape.id}" th:field="*{grapes.add()}">
</div>
</div>
====================PROBLEM=======================
<button class="btn btn-outline-success" type="submit" value="Submit">Save</button>
</form>
该表单正在创建一个Wine
具有名为"grapes"ArrayList
的对象的对象。其他输入字段工作正常,但我不知道如何绑定 arraylist 为每个复选框添加一个葡萄对象。它只是用来描述我正在尝试做的事情。Grape
th:field="*{grapes.add()}"
任何帮助表示赞赏!
解决方案
将
name
属性添加到您生成的复选框中,例如"grape"。因此,它们都将以相同的名称生成。当提交带有此类复选框的表单时,浏览器会为每个选定的复选框重复发送所选名称的值,例如grape=first&grape=third&grape=extra
在您的控制器中捕获此数据。这可以通过多种方式完成。
直接从以下获取参数
HttpServletRequest
:@RequestMapping(path="/admin", method=RequestMethod.POST) public void formSubmitted(HttpServletRequest request){ Map<String, String[]> allParams = request.getParameterMap(); // fetch all params String[] grapes = request.getparameterValues("grape"); // or just grapes }
使用
@RequestParam
注释@RequestMapping(path="/admin", method=RequestMethod.POST) public void formSubmitted(@RequestParam MultiValueMap<String, String> allParams, @RequestParam(name="grape", optional=true) List<String> grapes){ // your code }
不确定是否可以将此构造直接映射到对象的字段,但似乎您可以调整 Spring MVC 来做到这一点。
推荐阅读
- gitlab - 组或组详细信息页面上的 GitLab 500
- c - 我无法在 CMD 和 powershell 中执行 C 程序
- soundcloud - 如何获取某些播客的所有播放次数?
- c# - 如何在 C# 中使用 ListBox 更改焦点
- plotly-python - Plotly Express:绘图中元素的顺序(python)
- vb.net - 如何在矩形数组中的三个不同按钮单击上添加三个不同的矩形
- excel - VBA - Excel 在打开时延迟和强制停止宏
- javascript - 尝试添加 onclick 功能
- 标记但单击句柄功能未定义
- python - 将分区 Parquet 文件读取到 Python 中的 DataFame(在内存中),其中列类型是数组的数组
- asp.net-core - 找不到 Asp.net 核心身份模型命名空间名称