当我想在控制器中使用@ModelAttribute注释绑定用户输入时,为什么我的jsp页面会发送null?

时间:2015-03-02 16:26:45

标签: jsp spring-mvc request-mapping

当用户想要在数据库(book table)中添加新书时,我试图使用@ModelAttribute注释绑定用户输入。 Book类有四个属性(int bookId, String title, Author author, Publisher publisher)。用户只需输入标题,然后从下拉列表中选择作者和发布者。提交表单时,只有标题值来到控制器中的模型对象,作者和发布者为空。 我在下面提出我的表单和请求处理程序方法。任何人都可以说我的形式或者我的控制器类中的问题在哪里?

addBook.jsp

<form action="addBookExecution" method="post">
<table>
<tr>
    <td>Enter Book's Name:</td>
    <td><input type="text" name="title"/></td>
</tr>
<tr>
    <td>Select Author: </td>
    <td><select name="author">
                <option>****select author****</option>
                <c:forEach var="author" items="${authorList}">
                    <option value="${author}">${author.authorName}</option>
                </c:forEach>
        </select>
    </td>
</tr>
<tr>
    <td>Select Publisher: </td>
    <td><select name="publisher">
                <option>****select publisher****</option>
                <c:forEach var="publisher" items="${publisherList}">
                    <option value="${publisher}">${publisher.publisherName}</option>
                </c:forEach>
        </select>
    </td>
</tr>
<tr>
    <td>Click here to submit the form:</td>
    <td><input type="submit" value="submit"/></td>
</tr>

控制器:

@RequestMapping(value = "/addBookExecution", method = RequestMethod.POST)
protected ModelAndView addBookExecution(@ModelAttribute Book book)
        throws ClassNotFoundException, SQLException {
    bookService.addBook(book);
    ModelAndView model = new ModelAndView("adminFunctionsPage");
    model.addObject("Msg","Your request has been processed successfully.");
    return model;

}

1 个答案:

答案 0 :(得分:0)

我建议使用Spring Form

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<form:form method="POST" commandname="book" action="addBookExecution">
  <table>
   <tr>
     <td><form:label path="title">Enter Book's Name:</form:label></td> 
     <td><form:input path="title"></form:input></td>
  </tr>
  <form:select path="author" items="${authorList}" multiple="true"/>
   -----similarly do for other html element
</form:form>