猿问

如何将对象或数组从 html 页面发送到 POST 方法中

我有一个带有下一个代码的 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\ 块中,我使用复选框来初始化对象类型。字段 '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 方法中正确发送一组复选框值?


江户川乱折腾
浏览 242回答 1
1回答

天涯尽头无女友

第一条规则,使用复选框/单选按钮,您不会将未选中的项目返回到服务器,而只会将选中的项目返回给服务器。如果您将 HttpServletRequest 请求添加到 save() 方法的参数列表(它将由 Spring 自动填充),您应该能够调用request.getParameterValues("type")名称为“type”的所有复选框的值属性。您需要将所有这些复选框的值属性更新为 wd.getId() 而不是 wd.getType() 以便您拥有选中项目的 ID。最后,要指定初始选中/未选中状态,请使用th:checked="${wd.getType()}"th:value 代替(后者将需要保存如上所述的 id。)
随时随地看视频慕课网APP

相关分类

Java
我要回答