我正在尝试创建一个传递多个对象的表单。
我正在尝试创建一个表单,您可以在其中找到“产品
”和“客户
”并将它们添加到订单中。
我有 2 个模型类 Customer
和 Product
。 Customer
有 phoneNo
变量,Product
有 name
变量。
我发现传递多个对象的最简单方法是将它们添加到列表中并将 List
传递给 View
。这就是我正在做的事情,但是访问这些模型对象是另一回事。
Controller 类:
@Controller
public class OrderController {
@RequestMapping(value="/create_order", method= RequestMethod.GET)
public ModelAndView create_order() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("customer", new Customer());
model.put("product", new Product());
return new ModelAndView("create_order", "command", model);
}
}
页面:
<form:form method="POST" action="/Persistence_Web/order_confirmation" commandName="model">
<table>
<!-- I tried few different ways of writing it and all fail -->
<tr><form:label path="model[0].phoneNo">Customer phone number</form:label></tr>
<tr><form:input path="model[0].phoneNo"></form:input></tr>
....
最佳答案
引用属性Product.name
和Customer.phoneNo
在你的模型中,你必须引用你在模型中给出的名称加上属性名称(类中必须有一个 getter!!!)
<tr><form:input path="${customer.phoneNo}"></form:input></tr>
<tr><form:input path="${product.name}"></form:input></tr>
*如果您想在 View 中操作类中的属性,则它们必须具有 getter 和 setter。命名必须是:
private int attributeName
public int getAttributeName()
但是:只要类中的 getter 方法类似于 View 中的变量名称。您可以拥有getMyCalculation()
方法没有 myCalculation
属性,以便计算总计、平均值、格式化日期或需要在 View 中显示但不存储在模型中的任何内容。
此外,对于各种Products
或Customers
使用列表:
List<Customer> customers = // fill the list!!!
model.put("customers", customers);
并使用 <for:earch>
进行迭代
<c:forEach items="${customers}" var="customer">
<c:out value="${customer.phoneNo}"/>
</c:forEach>
关于java - Spring MVC - 从 JSP 中的列表访问表单中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29912971/