ModelAttribute not working with lists in spring

我的梦境 提交于 2019-12-11 20:43:03

问题


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:


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>


来源:https://stackoverflow.com/questions/26696974/modelattribute-not-working-with-lists-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!