Lets say we have an entity Person, a controller PersonController and an edit.jsp page (creating a new or editing an existing person)
Controller
@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>
Im trying the code above (without using the @ModelAttribute annotation in the savePerson method, and it works correct. Why and when do i need to add the annotation to the person object:
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String savePerson(@ModelAttribute("personToEditOrCreate") Person person, BindingResult result) {
personService.savePerson(person);
return "redirect:/home";
}
@ModelAttribute
inPUT
method – Badenpowell