Objects binding in Spring MVC form
controller, java, spring, spring-mvc
Solution
Create your own GroupEditor (that will populate the group object instance correcty) by extending PropertyEditorSupport. Then bind that in your controller :
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Group.class, new GroupEditor(groupService));
}
and your actual editor could look somethign like this :
public class GroupEditor extends PropertyEditorSupport{
private final GroupService groupService;
public GroupEditor(GroupService groupService){
this.groupService= groupService;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
Group group = groupService.getById(Integer.parseInt(text));
setValue(group);
}
}
Spring docs
Problem
I'm working on a test application using Spring MVC. I have a `Person` class and a `Group` class. Every `Person` object references a `Group` object. Now I implemented a jsp that show Person data and allow editing. Inside my form i put a select control to select the pearson's group: ``` <sf:select path="group"> <sf:options items="${groupList}" itemLabel="name" itemValue="id" /> </sf:select> ``` It shows the correct group when I load the page, but I cannot save changes, because in the controller I get only the string representing the group id. So, my question is: how can I obtain a `Group` object instead of its id in my controller? UPDATE Here my controller code: ``` @RequestMapping(value = "/details", params = "save", method = RequestMethod.POST) public String save(@ModelAttribute("person") Person p, BindingResult result) { this.personManager.savePerson(p); return "redirect:/people/details?id=" + p.getId(); } ```