【问题标题】:How do I bind a table in a form to a HashSet in Spring Boot?如何将表单中的表绑定到 Spring Boot 中的 HashSet?
【发布时间】:2018-05-03 05:55:39
【问题描述】:

我不太确定如何解决这个问题。我有一个由填充了产品信息的数据表呈现的表。我试图找出一个表格,我可以在其中插入数量和折扣值,然后保存数量> 0的选定字段或字段。然后将表数据绑定到集合或列表。

但是,我不太确定如何编写绑定。我在这里阅读了这个question,但它似乎并不完全相同,因为我认为我不能使用索引,因为可能有大量产品,因此响应中可能存在大量空值。任何帮助,将不胜感激。

Product.java

@Entity
@Table(name="products")
public class Product {
   @Getter
   @Setter
   @Id
   private Long productId;
   @Getter
   @Setter
   private Long productName; 
}

QuoteForm.java

public class QuoteForm {
   @Getter
   @Setter
   private Long quoteId;
   @Getter
   @Setter
   private Long contactId;
   @Getter
   @Setter
   private Set<ProductEntry> products;
 }

ProductEntry.java

public class ProductEntry {
  @Getter
  @Setter
  private TempProduct product;
  @Getter
  @Setter
  private Long quantity;
  @Getter
  @Setter
  private float discount;
}

form.html

<form id="productTable" th:object="${quoteForm}">
<input type="number" th:field="*{contactId}"></input>
<table id ="productList"
          class="table table-striped table-bordered"
          cellspacing="0"
          width="100%">
    <thead>
      <tr>
        <th>Name</th>
        <th>Quantity</th>
        <th>Discount</th>
      </tr>
   </thead>
   <tbody>
      <tr th:each="product : ${productData.getProducts()}">
      <td name="?">
          <a th:text="${product.getProductName()}"
                       th:href="@{|/product/records/${product.getProductId()}|}">
          </a>
      </td>
      <td>
          <input type="number" 
                 name="?" 
                 th:field="*{products.quantity}">
           </input>
      </td>
      <td>
         <input type="number" name="?" th:field="*{products.discount}"></input>
     </td>
    </tr>
  </tbody>

【问题讨论】:

    标签: spring forms spring-boot thymeleaf


    【解决方案1】:

    您可以使用“model.addAttribute()”进行绑定。你的控制器中有这样的东西:

    @RequestMapping("/example")
    public String formParse(Model model) {
        //some logic
    
        Set<ProductEntry> productList = //code to get();
    
        model.addAttribute("productList", productList);
    
        //some more logic
        return "yourView";
    }
    

    这里的“productList”是您分配给“?”的名称。 至于检查数量,您可以在表单本身中执行此操作,例如:

    &lt;div th:if="*{products.quantity&amp;gt;0}" th:field="*{products.quantity}"&gt;&lt;/div&gt;

    这里&gt表示“大于”。 希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2016-10-10
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      • 2010-09-22
      • 1970-01-01
      • 2019-10-19
      • 2015-08-06
      相关资源
      最近更新 更多