gpt4 book ai didi

java - Spring MVC - 从表单的 JSP 列表中访问对象

转载 作者:行者123 更新时间:2023-11-30 08:13:36 25 4
gpt4 key购买 nike

我正在尝试创建一个传递多个对象的表单。我正在尝试创建一个表单,您可以在其中找到“product”和“customer”并将它们添加到订单中。我有 2 个模型类 CustomerProductCustomerphoneNo 变量,Productname 变量。我发现传递多个对象的最简单方法是将它们添加到列表并将 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.nameCustomer.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 中显示但不存储在模型中的任何内容。

此外,对于各种 ProductsCustomers使用列表:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com