Spring Boot 2.5+Thymeleaf:表单提交传递Product对象及额外quantity参数
quantity Along with Product Object No worries, this is a common scenario and easy to fix. Here's how you can pass the quantity parameter alongside your Product object when submitting the form:
1. Update Your Thymeleaf Template
Add an input field for quantity inside your <form> tag. Since quantity isn't a property of the Product class, you don't need to use th:field—just set the name attribute to match the parameter name in your controller method:
<form method="post" th:object="${product}" th:action="@{/product}"> <!-- Existing Product fields here... --> <!-- Add this quantity input --> <input type="number" placeholder="Quantity" id="quantity" name="quantity" min="1" th:disabled="${isView}"/> <input th:type="${isView} ? hidden : submit" value="Submit"/> </form>
- The
name="quantity"is critical here—it tells Spring which request parameter maps to your controller'squantityargument. min="1"ensures users can't enter a non-positive quantity (adjust as needed for your use case).
2. Modify Your Controller Method
Update the submitProduct method to accept the quantity parameter. Spring will automatically bind the request parameter (from the input field) to this method argument:
@PostMapping(value = "/product") public String submitProduct(Product product, int quantity, Model model) { logger.info("submitProduct = " + product + ", quantity = " + quantity); // Your existing logic for add/update product if (product.getId() == 0) { product.setCreated(new Date()); } else { product.setUpdated(new Date()); } // You can now use the quantity value here (e.g., save to cart, etc.) return "redirect:/cart"; }
Optional: Handle Optional Quantity
If quantity might be optional (not always provided), change the parameter to Integer and use @RequestParam with required = false:
public String submitProduct(Product product, @RequestParam(required = false) Integer quantity, Model model) { // Handle null quantity if needed if (quantity == null) { quantity = 1; // Set a default value } // ... rest of your code }
How It Works
When you submit the form, Thymeleaf sends all form fields as request parameters. Spring's MVC automatic parameter binding matches the name attribute of the input field to the method parameter name (case-insensitive, but exact match is best practice). So the quantity input's value will be passed directly to your controller's quantity parameter.
内容的提问来源于stack exchange,提问作者Alexei

