Spring MVC,两个按钮与一个表单一起工作,它们如何协同工作?

时间:2015-03-06 09:34:21

标签: java spring jsp spring-mvc

enter image description here

我在这里做的是当我在教科书中输入书名并单击编辑按钮时。下面的文本框将显示本书的所有信息。然后我可以在相同的文本框中编辑信息。最后,我点击更新,新信息将被更新。我已完成编辑部分,我可以通过给定某个书名来编辑所有信息。现在我很困惑如何更新部分,因为编辑和更新都将使用相同的表单(那些文本框),然后如何处理发布或获取请求?有人可以向我解释一下吗?谢谢。

控制器:

@RequestMapping(value = "/edit", method=RequestMethod.GET)
public String getEditBookForm(@ModelAttribute("editBook") Book editBook, HttpServletRequest request) {

        return "editbook";
    }

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public ModelAndView processEditBookForm(@ModelAttribute("editBook") Book editBook ){

    ModelAndView mv = new ModelAndView("editbook");
    mv.addObject("resulteditBook",bookService.getBookByName(editBook.getBookName()) );
    return mv;
}

JSP:

<form:form modelAttribute="editBook" >

        <div>Enter BOOK NAME: <input type="text" name=bookName
                style="width: 100">

            <input type="submit" value="Edit" name="edit">
    </div>
    </form:form>

<form:form modelAttribute="updateBook" >
    ......
    <p>
        <input type="submit" value="Update" name="update">
    </p>
    </form:form>

2 个答案:

答案 0 :(得分:1)

您可以拥有类似

的内容
<input type="submit" class="button" name="edit" value="edit"/>
<input type="submit" class="button" name="update" value="update"/>

并根据参数区分您的控制器方法,例如用于编辑

@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "edit")
public String edit() {
...  
}

和更新

@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "update")
public String update() {
...  
}

答案 1 :(得分:0)

尝试这种方式

JSP

<form:form commandName="editBook" method="post" action="edit.do" id="editForm" >

        <div>Enter BOOK NAME: <input type="text" name=bookName
                style="width: 100">

            <input type="submit" value="Edit" name="edit"   onClick="editFormsubmit();">">
    </div>
    </form:form>

<form:form commandName="updateBook" method="post" action="update.do" id="updateForm"  >
    ......
    <p>
        <input type="submit" value="Update" name="update" onClick="updateFormsubmit();">
    </p>
    </form:form>

javascript

<script type="text/javascript" language="JavaScript">
function updateFormsubmit() {
     document.getElementById("updateForm").submit(); 
}

function editFormsubmit() {
     document.getElementById("editForm").submit(); 
}
</script>

控制器

@RequestMapping(value = "/edit", method=RequestMethod.GET)
public String getEditBookForm(@ModelAttribute("editBook") Book editBook, HttpServletRequest request) {

        return "editbook";
    }

@RequestMapping(value = "/update", method = RequestMethod.POST)
public ModelAndView processEditBookForm(@ModelAttribute("updateBook") Book editBook ){
    ModelAndView mv = new ModelAndView("editbook");
    mv.addObject("resulteditBook",bookService.getBookByName(editBook.getBookName()) );
    return mv;
}