3

我需要对 Spring 3.0 MVC 和 @ModelAttribute 带注释的方法参数进行一些说明。我有一个看起来像这样的控制器:

RequestMapping(value = "/home")
@Controller
public class MyController {

 @RequestMapping(method = RequestMethod.GET)
 public ModelAndView foo() {

               // do something
 }

@RequestMapping(method = RequestMethod.POST)
public ModelAndView bar(
        @ModelAttribute("barCommand") SomeObject obj) {

                    // do sometihng with obj and data sent from the form
}


}

在我的 home.jsp 上,我有一个像这样的表单,它将他的数据发送到 MyController 的 RequestMethod.POST 方法

<form:form  action="home"  commandName="barCommband">

</form:form

现在如果我尝试访问 home.jsp 我得到这个异常:

java.lang.IllegalStateException:
Neither BindingResult nor plain target object for bean name 'barCommand' available as  request attribute

为了解决这个问题,我发现我需要添加

@ModelAttribute("barCommand") SomeObject obj 

MyController 的 Request.GET 方法的参数,即使我不会在该方法中使用 obj。例如,如果使用不同的 commandName 向 home.jsp 添加另一个表单,如下所示:

<form:form  action="home/doSomething"  commandName="anotherCommand">

</form:form

我还必须在 RequestMethod.GET 上添加该参数,现在看起来像:

@RequestMapping(method = RequestMethod.GET)
 public ModelAndView foo( @ModelAttribute("barCommand") SomeObject obj1,
  @ModelAttribute("anotherCommand") AnotherObj obj2) {

               // do something
 }

或者我得到同样的例外。我要问的是这是正常的 Spring 3 MVC 行为还是我做错了什么。为什么我需要将所有 @ModelAttribute 参数放在 RequestMethod.GET 方法上?

提前感谢您的帮助

斯特凡诺

4

1 回答 1

3

是spring mvc参考。简单浏览了一下,发现了两种方法:

  1. @InitBinder
  2. @ModelAttribute("bean_name") 与方法。

您可以首先使用自定义数据绑定,从而即时创建命令对象。其次,您可以使用它注释方法并使用此名称预填充模型属性:

@ModelAttribute("bean_name")
public Collection<PetType> populatePetTypes() {
    return this.clinic.getPetTypes();
} 

如果它为空,我希望它会用名称“bean_name”填充模型属性。

于 2011-11-18T10:08:33.760 回答