簡體   English   中英

Spring MVC-從JSP中的列表訪問表單的對象

[英]Spring MVC - accessing objects from a list in JSP for a form

我正在嘗試創建帶有多個對象的表單。 我正在嘗試創建一個表單,您可以在其中找到“ product ”和“ customer ”並將其添加到訂單中。 我有2個模型類CustomerProduct CustomerphoneNo變量, Productname變量。 我發現傳遞多個對象的最簡單方法是將它們添加到list並將List傳遞給View 這就是我正在做的事情,但是訪問那些模型對象卻是另一回事。

控制器類:

 @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>

*如果要在視圖中操作它們,則類中的屬性必須具有getter和setter。 命名必須是:

private int attributeName
public  int getAttributeName()

但是 :只要類中的getter方法就像視圖中的變量名一樣。 您可以使用不帶 myCalculation屬性的getMyCalculation()方法,以計算總計,平均值,格式化日期或需要在視圖中顯示但不存儲在模型中的任何內容。

另外,對於各種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>

據我了解您的問題,您不能以這種方式訪問​​模型對象。 請嘗試使用Spring占位符${command.get('customer').phoneNo}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM