如何将从 ArrayList 生成的复选框中的值发布到另一个对象 ArrayList 中具有 Thymeleaf 和 S



我有一个表单,它从用户那里获取多个输入来创建对象,其中一个输入是一组复选框。

复选框是从具有ArrayListModel生成的,该带有名为"GrapeList">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对象,该对象具有一个ArrayList,其中包含称为"葡萄">Grape对象。其他输入字段工作正常,但我不知道如何绑定数组列表以为每个复选框添加一个葡萄对象。th:field="*{grapes.add()}"只是用来描述我正在尝试做的事情。

任何帮助不胜感激!

  1. name属性添加到生成的 checbox,例如"葡萄"。因此,它们都将以相同的名称生成。当提交带有此类复选框的表单时,浏览器为每个选定的复选框重复发送所选名称的值,例如

    grape=first&grape=third&grape=extra

  2. 在控制器中捕获此数据。这可以通过多种方式完成。

    • 直接从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来执行此操作。

相关内容

最新更新