Spring表单支持对象作为列表始终返回null

时间:2016-06-13 14:54:08

标签: java spring-mvc

    //Controller class
    @Controller
    public class ListController 
    {
        @Autowired
        LanguageDao ldao;


        @RequestMapping(value="doget" , method=RequestMethod.GET)
        public ModelAndView doGet()
        {
            List<Language> lang = ldao.getActiveLanguage();
            LanguageAndBeanTogether lab = new LanguageAndBeanTogether();
            for(Language l: lang)
            {
                LanguageAndDescription lad = new LanguageAndDescription(l.getLanguageCode(), l.getLanguageFlag(), "");
                lab.getLlist().add(lad);
            }
            System.out.println("total item in list is "+lab.getLlist().size());
            ModelAndView mav = new ModelAndView("viewForm","command",lab);
            return mav;
        }

        @RequestMapping(value="dopost",method=RequestMethod.POST)
        public ModelAndView doPost(LanguageAndBeanTogether landb)
        {
            System.out.println(landb);
            ModelAndView mav = new ModelAndView("viewForm","command",landb);
            return mav;

        }
    }

    //JSP file
      <form:form action="dopost.do">
        product name
        <form:input path="base.productName"/><br>

            <c:forEach var="language" items="${command.llist}" varStatus="vs" >
            <form:hidden path="llist[${vs.index}].languageCode"/>
                <img src="admin/language/original/${language.keyVal}"  />

                 <form:input  path="llist[${vs.index}].valueVal" />

            </c:forEach>
            <input type='submit'/>
        </form:form>

    //class containing list
    public class LanguageAndBeanTogether 
    {
        ProductCategory base;
        List<LanguageAndDescription> llist;
    //setter and getter
    }


    public class LanguageAndDescription 
    {
        String languageCode,keyVal,valueVal;
    //setter and getter
    }

public class Language 
{
    Integer id;
    String languageName,languageCode,languageFlag,isDefault,status;
//setters and getters
}

在上面的问题中,我总是得到表单支持对象的null值,即LanguageAndBeanTogether。请给我一个解决方案。我有另一个问题,是否有办法将两个对象绑定为spring中的表单后备对象。 非常感谢任何帮助。谢谢

2 个答案:

答案 0 :(得分:0)

您需要在html表单中引用列表中的元素:

yourList[anIndex].aProperty

例如

<form:form method="post" action="myAction" modelAttribute="productsForm">
   ...
   <input name="products[3].name />
   ...
</form:form>

引用第四个产品的名称,其中products是表单对象bean(productsForm)中的列表。

答案 1 :(得分:0)

您可以尝试向ModelAndView添加属性

ModelAndView mav = new ModelAndView("viewForm");
mav.addAttribute("command",landb)

它将以$ {command}

的形式提供