2012-04-13 2 views
2

Spring MVC를 사용하여 테스트 애플리케이션을 만들고있다. 나는 Person 클래스와 Group 클래스를 가지고 있습니다. Person 개체는 모두 Group 개체를 참조합니다.Spring MVC 형식의 객체 바인딩

이제 Person 데이터를 표시하고 편집을 허용하는 jsp를 구현했습니다. 내 양식 내부 내가 피어슨의 그룹을 선택하는 선택 제어를 넣어 :

<sf:select path="group"> 
    <sf:options items="${groupList}" itemLabel="name" itemValue="id" /> 
</sf:select> 

그것은 내가 페이지를로드 할 올바른 그룹을 보여 주지만, 컨트롤러에서 I 그룹을 대표하는 유일한 문자열을 얻을 수 있기 때문에이 변경 내용을 저장할 수 없습니다 id.

제 질문은 : 컨트롤러에서 ID 대신 Group 개체를 어떻게 얻을 수 있습니까? 여기

UPDATE 내 컨트롤러 코드 :

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

답변

6

자신의 GroupEditor 만들기 PropertyEditorSupport을 확장하여 (즉, 그룹 개체 인스턴스 올바르게 기능을 채 웁니다).

@InitBinder 
protected void initBinder(WebDataBinder binder)  { 
     binder.registerCustomEditor(Group.class, new GroupEditor(groupService)); 
} 

및 실제 편집기는 다음과 같이 somethign 볼 수 있었다 : 그런 다음 컨트롤러가 결합

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

+0

내가 내 질문에 업데이트 ... 무슨 – davioooh

+0

나는에서 변경해야 내 방법 서명? 이 방법을 바꿔야합니까 'public String save (@ModelAttribute ("person") Person p, Group g, BindingResult result)'? – davioooh

+0

원래 질문과 같으면 아무것도 표시되지 않습니다. 바인딩 결과는 유효성을 검사하는 경우에만 필요합니다 ... – NimChimpsky