我有以下域物件:
public class Pizza extends AbstractProduct {
public enum Size { SMALL, MEDIUM, LARGE }
private Size size;
private List<Ingredient> ingredients;
// Getters and setters
}
此物件包含成分物件串列:
public class Ingredient {
public enum Type { SAUCE, VEGGIES, PROTEIN, CHEESE }
private int id;
private String name;
private Type type;
// Getters and setters
}
我想在 2 個控制器之間傳遞 Pizza 物件。
首先,我從 Pizza 服務中檢索 Pizza 物件并將其傳遞給視圖。
@Controller
@RequestMapping("/pizzas")
public class PizzaController {
@GetMapping("/{id}")
public String getPizzaInfo(@PathVariable int id, Model model) {
Pizza pizza = // Getting pizza
model.addAttribute("pizza", pizza);
return "pizza/pizza-info";
}
}
然后,用戶單擊“添加到購物車”按鈕,發送 POST 請求,我在 CartController 中收到此請求。
@Controller
@RequestMapping("/cart")
public class CartController {
@PostMapping("/add-pizza")
public String addPizzaToOrder(@ModelAttribute Pizza pizza) {
// Order business logic
}
}
我使用 html 隱藏輸入從 PizzaController 中傳遞的 Pizza 物件獲取資料。
<form method="post" th:object="${pizza}" th:action="@{/cart/add-pizza}">
<input type="hidden" th:field="${pizza.id}" id="id">
<input type="hidden" th:field="${pizza.name}" id="name">
<input type="hidden" th:field="${pizza.price}" id="price">
<input type="hidden" th:field="${pizza.imageUrl}" id="img_url">
<label>
<select name="size">
<option th:each="size : ${T(pizzaonline.service.domain.Pizza.Size).values()}"
th:value="${size}" th:text="${size}"></option>
</select>
</label>
<button>Add to cart</button>
</form>
除了一個領域 - 成分外,一切都很好。我需要在語意上等同<input type="hidden" th:field="${pizza.ingredients}" id="ingredients">于復制成分串列的東西。我怎樣才能做到這一點?
uj5u.com熱心網友回復:
如果你想像做披薩一樣做,它看起來像這樣:
<th:block th:each="ingredient, status: ${pizza.ingredients}">
<input type="hidden" th:field="*{ingredients[__${status.index}__].id}" />
<input type="hidden" th:field="*{ingredients[__${status.index}__].name}" />
<input type="hidden" th:field="*{ingredients[__${status.index}__].type}" />
</th:block>
您還可以查看使用@SessionAttributes控制器上的屬性,并簡單地省略所有隱藏欄位。它將在會話中臨時存盤指定的模型屬性,并保留已經指定的欄位的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/405726.html
標籤:
