2009-05-13 1 views
1

스프링 폼이있는 JSP가 있습니다. 폼의 명령 객체는 JSP가 렌더링되기 전에 컨트롤러에 추가됩니다. Spring은 JSP의 폼을이 명령 객체에 바인딩하고 NEW 인스턴스를 제출할 때이를 올바르게 처리합니다.스프링 바인딩 전에 @RequestMapping 메소드에서 명령 객체를 수동으로 설정할 수 있습니까?

그러나 DWR (올바르게 작동 함)을 통해 명령 개체를 유지하고 컨트롤러에 양식을 제출하고 싶습니다. 양식이 컨트롤러에 제출되면 명령 객체는 더 이상 새로운 객체가 아니라 업데이트해야하는 지속 객체입니다. 여기서 양식 요소가 자동으로 명령 개체에 바인딩되고 바인딩을 통해 업데이트되지만 바운드되지는 않습니다.

간단한 예 : ModelMap에 새 Task을 추가하여 스프링 양식이 해당 명령 개체에 바인딩되도록합니다. 그러나 새 Task을 제출하는 대신 ID 번호를 반환하는 DWR을 통해 새 Task을 유지 한 다음 양식을 컨트롤러에 제출하기 전에 작업을 계속 편집합니다.

컨트롤러 클래스

@Controller 
public class ProjectController { 

    /** 
    * This adds the "task" command object to the session attributes and loads 
    * the initial form. 
    */ 
    @RequestMapping(value="/project", method=RequestMethod.GET) 
    public String setupForm(@RequestParam(value="id", required=true) String id, 
          HttpServletRequest request, ModelMap modelMap) { 

     modelMap.addAttribute("project", projectRepo.get(id)); 
     modelMap.addAttribute("task", new Task()); 

     return "/project/task"; 
    } 

    /** 
    * This processes the form submit, and should update the Task. 
    */ 
    @RequestMapping(value="/project/task/update", method=RequestMethod.POST) 
    public String updateTask(@ModelAttribute(value="task") Task task, 
          @RequestParam(value="taskId") String taskId, 
          HttpServletRequest request, ModelMap modelMap) { 

     // BEFORE binding the parameters to the command object (task), 
     // I want to assign the command object as the one already persisted. 
     task = taskRepo.get(taskId); 

     // NOW, I want the request parameters to be bound to the task command object. 
     // HOW ????????? 

     // Persist the changes. 
     taskRepo.merge(task); 

     // BACK to the setupForm method/form view 
     return "/project?id=" + task.getProject().getId(); 
    } 
} 

봄 양식

<form:form commandName="task" method="post" action="/project/task/update" id="taskForm"> 
    <form:hidden path="id" id="task.id"/> 
    <form:input path="name" id="task.name"/> 
    <!-- DWR will save the task (save and continue), then will return the id. --> 
    <!-- After saved, the user can still change the name, 
     then submit the form for processing by the controller --> 
</form:form> 

은 봄 바인딩 명령 개체는 해당되는 사항이있는 바인딩 포스트 제출 전에 영속 객체로 설정 할 수 있습니까?

+0

예, 양식을 제출하기 전에 명령 개체를 수정할 수 있어야합니다. 몇 가지 코드를 알려주시겠습니까? 당신이 현재하고있는 일이나 성취하고자하는 일을 정말로 이해하지 못합니다. –

+0

나는 내가하는 일의 간단한 예를 덧붙였다. – Matt

답변

3

실제로 주석을 사용하여 더 좋은 방법이 있습니다.

리포지토리에서 원하는 명령 개체를 반환하는 ModelAttribute 메서드를 만듭니다.

@ModelAttribute("task") 
public Task task(@RequestParam(value = "id", required = true) String id) { 
    return taskRepo.get(taskId); 
} 

그런 다음, 단순히 양식 제출 방법에 ModelAttribute 모 데르를 추가합니다.

@RequestMapping(value="/project/task/update", method=RequestMethod.POST) 
public String updateTask(@ModelAttribute(value="task") Task task, 
         HttpServletRequest request, ModelMap modelMap) { 

    taskRepo.merge(task); 
    ... 
} 
1

@ModelAttribute을 사용하여 명령 개체에 액세스 할 때 명령 개체에 액세스하기 전에 바인딩이 발생하는 것으로 보입니다. 요청 매개 변수를 양식에서 바인딩하기 전에 원하는 명령 오브젝트를 설정하려면 속성 ID를 전달하여 데이터베이스에서 가져온 다음 WebRequest 매개 변수를 바인드하십시오. 당신이 응용 프로그램의 이러한 유형의 '바인딩 수동으로 데이터'의 Juergen Hoeller's 예를 찾을 수있는 POST 메소드

@RequestMapping(value="/project/task/update", method=RequestMethod.POST) 
public String updateTask(@ModelAttribute(value="task") Task task, 
         @RequestParam(value="taskId") String taskId, 
         HttpServletRequest request, ModelMap modelMap) { 

    // BEFORE binding the parameters to the command object (task), 
    // I want to assign the command object as the one already persisted. 
    task = taskRepo.get(taskId); 

    // NOW, I want the request parameters to be bound to the task command object. 
    WebRequestDataBinder binder = new WebRequestDataBinder(task); 
    ServletWebRequest webRequest = new ServletWebRequest(request); 
    binder.bind(webRequest); 

    // Persist the changes. 
    taskRepo.merge(task); 

    // BACK to the setupForm method/form view 
    return "/project?id=" + task.getProject().getId(); 
} 

Spring 2.5.x documentation of WebRequestDataBinder에서

이다.

MyBean myBean = new MyBean(); 
// apply binder to custom target object 
WebRequestDataBinder binder = new WebRequestDataBinder(myBean); 
// register custom editors, if desired 
binder.registerCustomEditor(...); 
// trigger actual binding of request parameters 
binder.bind(request); 
// optionally evaluate binding errors 
Errors errors = binder.getErrors(); 
... 
+0

AnnotationMethodHandlerAdapter의 BindingInitializer에 연결된 속성 편집기를 추가로 활용할 수도 있습니다.이렇게하려면 AnnotatioNMethodHandlerAdapter가 사용하는 선언 된 BindingInitializer를 가져 와서'initBinder (binder, webRequest)'를 호출하십시오 : @Autowired private BindingInitializer bindingInitializer; -------- bindingInitializer.initBinder (binder, webRequest); – Matt

+0

스프링이 요청에 오류 객체를 자동으로 넣는가? 아니면 수동으로해야합니까? – Anthony

관련 문제