java - 为 POST 请求绑定(bind) Thymeleaf 模板上嵌入的对象列表

标签 java spring-mvc thymeleaf

我正在开发一个杂货店列表 Web 应用程序。一项功能应该是检查(取消)检查列表中找到/购买的元素。显示所有值效果很好。但是,当我检查一些购买的元素上的一些复选框并尝试稍后发布它时,Spring MVC Controller 中传入的 @ModelAttribute 为空(除了 id)。

希望你能帮助我。

这是我的类(class):

public class PurchaseList {

private Long id;
private List<PurchaseItem> purchaseItemList;
private DateTime purchaseDate;
private boolean done;
}


public class PurchaseItem {

private Long id;
private String purchaseItemName;
private PurchaseCategory purchaseCategory;
private PurchaseList purchaseList;
private boolean found;
}

Controller :

@RequestMapping(value="/{id}", method=RequestMethod.POST)  
public String postPurchaseList(@PathVariable(value="id") Long id, @ModelAttribute("purchaseList") PurchaseList purchaseList, Model model) {
  List<PurchaseList> notDonePurchaseList = purchaseListService.getNotDonePurchaseList();
  model.addAttribute("notDonePurchases", notDonePurchaseList);
  purchaseListService.savePurchaseList(purchaseList);
  return "purchaseList";
}

Thymeleaf 模板

<form action="#" th:action="@{/purchaseList/{purchaseListId}/(purchaseListId=${purchaseList.id})}" th:object="${purchaseList}" method="post">
      <table class="table table-bordered table-hover">
        <thead>
          <tr>
            <td>Found</td>
            <td>Item</td>
            <td>Category</td>
          </tr>
        </thead>
        <tr th:each="item,status : ${purchaseList.purchaseItemList}">
          <td><input type="checkbox" th:checked="${item.found}" th:value="*{purchaseItemList[__${status.index}__].found}" /></td>
          <td th:text="${item.purchaseItemName}"></td>
          <td th:text="${item.purchaseCategory.categoryName}"></td>
        </tr>
      </table>
      <input type="submit" value="Submit" id="submit" />
      </form>

我知道我没有设置其他值(仅设置 found 属性)。或者这就是问题所在?

致以诚挚的问候

编辑:

  1. 按照 ArrayList buyItemList 的建议进行初始化。现在,一个空的 ArrayList 返回到 Controller 。

最佳答案

在PurchaseList类中初始化purchaseItemList。 public class PurchaseList { private Long id; private List<PurchaseItem> purchaseItemList=new ArrayList<>(); private DateTime purchaseDate; private boolean done; }

为输入字段指定一个像这样的 id。

<td><input type="checkbox" th:checked="${item.found}" th:value="* {purchaseItemList[__${status.index}__].found}" th:id='purchaseList.purchaseItemList[__${status.index}__].found'/></td>

关于java - 为 POST 请求绑定(bind) Thymeleaf 模板上嵌入的对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40662370/

相关文章:

java - Spring MVC - 请求语法不正确

java - Thymeleaf:无法传递隐藏 th:field 的预定义值

java - Ant和XML配置文件解析

java - Spring 安全秒 :authorize tag using Java Config

java - tomcat多线程问题

java - MockMvc 测试 OPTIONS 请求

spring - thymeleaf : template might not exist or might not be accessible by any of the configured Template Resolvers

java - 如何从 spring boot thymeleaf 获取输入值到java类?

java - Android SDK 可以与 JDK 1.7 一起使用吗?

java - 基于多个参数的对象列表排序