【问题标题】:Thymeleaf - How to POST a fixed object to controller?Thymeleaf - 如何将固定对象发布到控制器?
【发布时间】:2018-09-23 01:49:54
【问题描述】:

我有一组复选框,每个复选框都代表一个“产品”的顶部。我想传递一个修改后的“产品”对象,并将选中的“浇头”存储为“selectedToppings”。

我已经尝试了下面的代码,但它不起作用。问题是我传递了一个空的“产品”对象,并且只存储了复选框值(作为“selectedToppings”)。 如何将“product”对象与“selectedToppings”一起传递?

html(片段):

            <form method="post" th:object="${product}" th:action="@{/addItemToCart}">
            <div class="modal-body">
                    <div class="card-body">
                        <div th:each="topping : ${product.toppings}">
                            <div class="custom-control custom-checkbox my-1 mr-sm-2">
                                <input type="checkbox" class="custom-control-input" th:id="${topping} + ${product.id}" name="toppings" th:value="${topping}" />
                                <label class="custom-control-label" th:for="${topping} + ${product.id}" th:text="${topping}"></label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-block btn-success">Add to Shopping Cart</button>
                </div>
            </form>

控制器:

@RequestMapping(value="/addItemToCart", method=RequestMethod.POST)
public String addItemToCart(@ModelAttribute("product") Product product, @RequestParam("toppings") List<String> toppings)
{
    Product newItem = product;
    newItem.setSelectedToppings(toppings);
    addItemToBucket(newItem);

    return "redirect:/menu";
}

实体:

public class Product
{
private String id;
private String name;
private String description;
private Double price;
private List<String> toppings;
private List<String> selectedToppings;

public Product()
{
 this.id = "";
 this.name = "";
 this.description = "";
 this.price = 0.0;
 this.toppings = new ArrayList<String>();
 this.selectedToppings = new ArrayList<String>();
}
public Product(String id, String name, String description, Double price, List<String> toppings)
{
    this.id = id;
    this.name = name;
    this.description = description;
    this.price = price;
    this.toppings = toppings;
    this.selectedToppings = new ArrayList<String>();
}
//...getters & setters
}

【问题讨论】:

  • 是的,您可以将多个对象传递给控制器​​。这会很有帮助stackoverflow.com/questions/16122257/…
  • @JaisAnkit 我有兴趣在问题的上下文中将对象传递给控制器​​

标签: spring-mvc spring-boot thymeleaf


【解决方案1】:

我不确定我是否完全理解你的问题。

如果您在 &lt;input&gt; 标签上添加以下内容,它应该可以工作。

th:field="*{toppings}"

我现在注意到的一件事是,您的 Product 类缺少 getter/setter。

【讨论】:

  • 如果您执行 product.getToppings() 会看到什么?顺便说一句,您的实体类 Product 有 getter/setter 吗?
  • “toppings”变量填写正确。但是该对象的其余部分是空的。是的,我有每个变量的 getter/setter。
  • 其他变量将为空,因为您的表单上除了浇头之外没有任何其他字段。
  • 我已将“产品”作为模型属性传递。 product.selectedToppings 是唯一的空变量,我想从用户那里得到填充。有可能吗?
  • 如果你想要的只是一个参数,为什么你必须映射到 Product 类?
猜你喜欢
  • 2019-05-20
  • 1970-01-01
  • 2016-08-05
  • 2019-09-29
  • 2018-09-02
  • 2014-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多