为了账号安全,请及时绑定邮箱和手机立即绑定

是否可以使用 Thymeleaf 从列表中发布一个特定项目?

是否可以使用 Thymeleaf 从列表中发布一个特定项目?

三国纷争 2021-08-19 13:33:49
在我的 Spring Boot 应用程序中,我有以下内容RequestMapping:@GetMapping("/test")public String get(Model model) {    List<CustomItem> items = itemService.findAll();    model.addAttribute("items", items);    return "test";}我将这些项目显示在一个简单的 HTML 表格中(一行表示一个项目)。我想向每一行添加一个按钮,该按钮仅提交与CustomItem端点相对应的内容,如下所示:@PostMapping("/test")public String post(CustomItem item) {    // doing something with item    return "redirect:/test";}我试过的是form为每一行创建一个单独的:<table> <tr th:each="item, stat : ${items}">  <td>   <form th:object="${items[__${stat.index}__]}" th:action="@{/test}" method="post">    <input type="text" th:field="${items[__${stat.index}__].someField}">    <button type="submit">Submit</button>   </form>  </td> </tr></table>但是我在导航到页面时收到以下错误:BindingResult 和 bean 名称“items[0]”的普通目标对象都不能用作请求属性我也尝试了以下方法:<table> <tr th:each="item, stat : ${items}">  <td>   <form th:object="${item}" th:action="@{/test}" method="post">    <input type="text" th:field="*{someField}">    <button type="submit">Submit</button>   </form>  </td> </tr></table>在这种情况下,错误如下:BindingResult 和 bean 名称“item”的普通目标对象都不能用作请求属性我无法弄清楚我的方法有什么问题,所以我真的很感激任何建议。
查看完整描述

2 回答

?
函数式编程

TA贡献1807条经验 获得超9个赞

这对我有用:


在控制器中实例化 item 并设置为模型:


@GetMapping("/test")

public String get(Model model) {

    List<CustomItem> items = itemService.findAll();

    model.addAttribute("items", items);

    model.addAttribute("item", new CustomItem());

    return "test";

}

HTML:


<table>

        <tr th:each="i : ${items}">

            <form th:action="@{/test}" method="post" th:object="${item}">


                <td th:text="${i.id}" />

                <td th:text="${i.name}" />

            <td><input type="hidden" th:value="${i.id}" name="id" />

                <input type="hidden" th:value="${i.someField}" name="someField" />

                <button type="submit" name="action" value="remove">OK</button></td>

            </form>

        </tr>

    </table>

并在控制器中创建一个方法来处理该项目:


@PostMapping("/test")

    public String test(@ModelAttribute CustomItem item,HttpServletRequest request) {

        doStuff(item);

    }


查看完整回答
反对 回复 2021-08-19
?
米脂

TA贡献1836条经验 获得超3个赞

我通过简单地使用th:value和name属性而不是th:field:


<table>

 <tr th:each="item : ${items}">

  <td>

   <form th:action="@{/test}" method="post">

    <input type="text" th:value="${item.someField}" name="someField">

    <button type="submit">Submit</button>

   </form>

  </td>

 </tr>

</table>


查看完整回答
反对 回复 2021-08-19
  • 2 回答
  • 0 关注
  • 143 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信