ModelAttribute not working with lists in spring

2019-09-18 14:42发布

I want to bind a List using ModelAttribute. The list contains objects of type Transaction each of which contains transactionid (type int). This is my controller code:

@RequestMapping(value = "/approvecreditdebit.do", method = RequestMethod.POST)
    public ModelAndView doActions(HttpServletRequest request,
            @ModelAttribute("clc") Clc transactionList, BindingResult result,
            ModelMap model) {
        /*
         * switch (action) { case "approve":
         */

        System.out.println("Obj = " + transactionList.getClass());
        System.out.println("Val = " + transactionList.getTransactionList());
        Users users = new Users();
        return new ModelAndView("internal","internal",users);
    }

This is my jsp code:

<form:form action="approvecreditdebit.do" method="POST"
    modelAttribute="clc">

    <table border="1">
        <tr>
            <th>no</th>
            <th>ID</th>
        </tr>

        <c:forEach items="${clc.transactionList}"
            var="transaction" varStatus="status">
            <tr>
                <td>${status.index}</td>
                <td><input name = "transaction[${status.index}].transactionId"
                        value="${transaction.transactionId}" /></td>
            </tr>
        </c:forEach>
    </table>

    <br>
    <br>

    <center>
        <input type="submit" value="approve" />
    </center>


</form:form>

This is the Clc class:

public class Clc{

    private List<Transaction> transactionList;

    public List<Transaction> getTransactionList() {
        return transactionList;
    }

    public void setTransactionList(List<Transaction> transactionList) {
        this.transactionList = transactionList;
    }    
}

The value of transactionList is not being set to the values received from the form. I receive the following error:

Request processing failed; nested exception is java.lang.NullPointerException

I tried searching for the solution on google and got a lot of solutions from stackoverflow but none of them seem to work.

1条回答
女痞
2楼-- · 2019-09-18 15:26

Try something like this (notice the use of <form:input>). I just tried it on a simple Spring MVC app and it works (list is not null and has the values from the form when I try to access it in my POST method).

<c:forEach var="transaction" varStatus="status" items="${clc.transactionList}">
    <tr>
        <td>${status.index}</td>
        <td><form:input path="transactionList[${status.index}].id" /></td>
    </tr>
</c:forEach>
查看更多
登录 后发表回答