首页 > 解决方案 > 如何将 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 为每个复选框添加一个葡萄对象。它只是用来描述我正在尝试做的事情。Grapeth:field="*{grapes.add()}"

任何帮助表示赞赏!

标签: javaspring-bootspring-mvcthymeleaf

解决方案


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

    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 来做到这一点。


推荐阅读