Thymeleaf - 如何将固定对象发布到控制器?

时间:2018-04-12 19:31:05

标签: spring-mvc spring-boot thymeleaf

我有一系列复选框,其中每个复选框代表一个'产品的顶部。我想传递经过修改的产品'已检查'浇头的对象'存储为' selectedToppings'。

我已尝试过以下代码,但它不起作用。问题是我通过一个空的产品'对象和仅存储复选框值(作为' 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
}

1 个答案:

答案 0 :(得分:0)

我不确定,如果我完全理解你的问题。

如果您在<input>标记上添加以下内容,则应该有效。

th:field="*{toppings}"

我现在注意到的一件事是,你缺少产品类的getter / setter。