2

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();
}
0

1 Answer 1

6

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

2
  • What do I have to change in my method signature? Do I have to change this way public String save(@ModelAttribute("person") Person p, Group g, BindingResult result) ?
    – davioooh
    Apr 13, 2012 at 10:09
  • Nothing if its the same as your original question. The binding result is only necessary if you are validating it ... Apr 13, 2012 at 10:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.