猿问

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

在我的 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”的普通目标对象都不能用作请求属性


我无法弄清楚我的方法有什么问题,所以我真的很感激任何建议。


三国纷争
浏览 144回答 2
2回答

函数式编程

这对我有用:在控制器中实例化 item 并设置为模型:@GetMapping("/test")public String get(Model model) {&nbsp; &nbsp; List<CustomItem> items = itemService.findAll();&nbsp; &nbsp; model.addAttribute("items", items);&nbsp; &nbsp; model.addAttribute("item", new CustomItem());&nbsp; &nbsp; return "test";}HTML:<table>&nbsp; &nbsp; &nbsp; &nbsp; <tr th:each="i : ${items}">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <form th:action="@{/test}" method="post" th:object="${item}">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td th:text="${i.id}" />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td th:text="${i.name}" />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td><input type="hidden" th:value="${i.id}" name="id" />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="hidden" th:value="${i.someField}" name="someField" />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button type="submit" name="action" value="remove">OK</button></td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </form>&nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; </table>并在控制器中创建一个方法来处理该项目:@PostMapping("/test")&nbsp; &nbsp; public String test(@ModelAttribute CustomItem item,HttpServletRequest request) {&nbsp; &nbsp; &nbsp; &nbsp; doStuff(item);&nbsp; &nbsp; }

米脂

我通过简单地使用th:value和name属性而不是th:field:<table>&nbsp;<tr th:each="item : ${items}">&nbsp; <td>&nbsp; &nbsp;<form th:action="@{/test}" method="post">&nbsp; &nbsp; <input type="text" th:value="${item.someField}" name="someField">&nbsp; &nbsp; <button type="submit">Submit</button>&nbsp; &nbsp;</form>&nbsp; </td>&nbsp;</tr></table>
随时随地看视频慕课网APP

相关分类

Java
我要回答