【问题标题】:Problem with ModelAndView and ModelMap in AnnotationController, SpringframeworkSpringframework AnnotationController 中 ModelAndView 和 ModelMap 的问题
【发布时间】:2010-11-09 15:44:22
【问题描述】:

我有一个问题是 ModelAndView 和 ModelMap 之间的点差。

当 requestMethod 为“GET”且 requestMethod 为“POST”时,我想维护 modelAndView。 我的 modelAndView 救了别人。

所以我将 modelAndView 返回类型设置为“GET”、“POST”方法。

但是,如果请求因请求验证失败而在“POST”上返回 showForm,则请求丢失 commandObject、form:errors...。

示例)

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;

}

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    不清楚您的问题是什么,但关于 ModelMap 和 ModelAndView 之间的区别,它们来自 Spring MVC 的两个不同“世代”。 ModelAndView 来自 Spring 2.0 风格,而 ModelMap 是在 2.5 中引入的。

    一般来说,如果您的控制器是 Spring 2.0 控制器的子类,例如 SimpleFormController(我认为您的代码片段是),那么 ModelAndView 就是要使用的东西。如果您使用 Spring 2.5 @Controller 注解,最好使用 ModelMap。

    【讨论】:

      【解决方案2】:

      我的问题更多是关于如何在提交时将 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>
          ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-05-17
        • 1970-01-01
        • 2013-08-31
        • 2019-02-01
        • 1970-01-01
        • 2015-02-04
        • 2021-06-27
        相关资源
        最近更新 更多