Object properties editing with Spring Forms
I'm a bit confused about how an object could be edited with Spring Forms, for instance: suppose I have an object Person who has a lot of attributes because I obtain it from a dao, and I only want to provide the field "street" for editing, I would have this in my PeopleController开发者_如何学运维:
@RequestMapping("editPerson")
public void editPerson (Model model) {
Person person = dao.getThatPerson ();
model.addAttribute (person);
}
And in my view file I would have nothing but this:
<form:form method="post" action="" commandName="person">
<form:input path="street" />
<input type="submit" value="Edit!" />
</form:form>
So when I post the form, will the other attributes of the Person object be preserved? For instance person's name, surname, username, age, etc. Otherwise, how could this be accomplished?
Store your model object in session, like so:
@Controller
@SessionAttributes("person")
public class YourController {
...
@ModelAttribute("person")
public Person getPerson() {
return new Person();
}
@RequestMapping("editPerson")
public void editPerson (@ModelAttribute("person") Person person) {
person = dao.getThatPerson ();
}
@RequestMapping(value="postperson", method = RequestMethod.POST)
public void postPerson(@ModelAttribute("person") Person person) {
// do stuff with person
}
}
You're probably best just putting the person ID and street in the model, not the whole Person. When the user submits then just update the street by either;
1 - Providing an updateStreet(String street, int personID)
method in your DAO.
2 - Getting the person from the DAO, setting the street then persisting the new person.
精彩评论