2009-07-10 34 views
1

我有一個問題,即ModelAndView和ModelMap之間的點差異。AnnotationController中的ModelAndView和ModelMap存在問題,Springframework

當requestMethod爲「GET」且requestMethod爲「POST」時,我想維護modelAndView。 我的模型和視圖保存了其他人。

所以我把modelAndView的返回類型改爲「GET」,「POST」方法。

但是,請求丟失的commandObject,形式:錯誤...,如果請求返回showForm「POST」,因爲請求驗證失敗。

例子)

private ModelAndView modelAndView;  

public ControllerTest{ 
    this.modelAndView = new ModelAndView(); 
} 

@RequestMapping(method = RequestMethod.GET) 
public ModelAndView showForm(ModelMap model) { 
    EntityObject entityObject = new EntityObject(); 
    CommandObject commandObject = new CommandObject(); 
    commandObject.setEntityObject(entityObject); 
    model.addAttribute("commandObject", commandObject); 
    this.modelAndView.addObject("id", "GET"); 
    this.modelAndView.setViewName("registerForm"); 

    return this.modelAndView; 
} 

@RequestMapping(method = RequestMethod.POST) 
public ModelAndView submit(@ModelAttribute("commandObject") CommandObject commandObject, 
     BindingResult result, SessionStatus status) { 

    this.commandValidator.validate(commandObject, result); 

    if (result.hasErrors()) { 
     this.modelAndView.addObject("id", "POST"); 
     this.modelAndView.setViewName("registerForm"); 
     return this.modelAndView; 

    } else { 
     this.modelAndView.addObject("id", "after POST"); 
     this.modelAndView.setViewName("success"); 
    } 
    status.setComplete(); 
    return this.modelAndView; 

} 

回答

4

目前尚不清楚你的問題是什麼,但作爲ModelMap和ModelAndView上的區別,他們來自Spring MVC中的兩個不同的「代」。 ModelAndView來自Spring 2.0風格,而ModelMap則是在2.5中引入的。一般來說,如果你的控制器繼承了Spring 2.0控制器,比如SimpleFormController(我認爲你的代碼片段就是這樣),那麼ModelAndView是可以使用的。如果您使用Spring 2.5 @Controller註釋,ModelMap更可取。

0

我的問題更關注如何在提交時將html表單對象綁定到POJO。

Java代碼:

@RequestMapping(method = RequestMethod.POST) 
public String processRequest(ModelMap map, @ModelAttribute("accessRequestBean") AccessRequestBean accessRequestBean){ 
    logger.debug(accessRequestBean); 

    return("NOTHING"); 
} 

HTML代碼:

<@spring.bind "accessRequestBean" /> 
    <form> 
    ...