假设我们有一个实体Person,一个控制器PersonController和一个edit.jsp页面(创建一个新的或编辑一个现有的人)控制者@RequestMapping(value = "/edit", method = RequestMethod.POST)public String editPerson(@RequestParam("fname") String fname, Model model) { if(fname == null || fname.length() == 0){ model.addAttribute("personToEditOrCreate", new Person()); } else{ Person p = personService.getPersonByFirstName(fname); model.addAttribute("personToEditOrCreate", p); } return "persons/edit";}@RequestMapping(value = "/save", method = RequestMethod.POST)public String savePerson(Person person, BindingResult result) { personService.savePerson(person); return "redirect:/home";}edit.jsp<form:form method="post" modelAttribute="personToEditOrCreate" action="save"> <form:hidden path="id"/> <table> <tr> <td><form:label path="firstName">First Name</form:label></td> <td><form:input path="firstName" /></td> </tr> <tr> <td><form:label path="lastName">Last Name</form:label></td> <td><form:input path="lastName" /></td> </tr> <tr> <td><form:label path="money">Money</form:label></td> <td><form:input path="money" /></td> </tr> <tr> <td colspan="2"> <input type="submit" value="Add/Edit Person"/> </td> </tr> </table> </form:form>我正在尝试上面的代码(没有在savePerson方法中使用@ModelAttribute批注,并且它可以正常工作。为什么以及何时需要将批注添加到person对象:@RequestMapping(value = "/save", method = RequestMethod.POST)public String savePerson(@ModelAttribute("personToEditOrCreate") Person person, BindingResult result) { personService.savePerson(person); return "redirect:/home";}
- 2 回答
- 0 关注
- 554 浏览
添加回答
举报
0/150
提交
取消