我需要一些关于 Spring 3.0 MVC 和 @ModelAttribute 注释方法参数的说明。我有一个看起来像这样的 Controller :
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 方法上?
在此先感谢您的帮助
斯特凡诺
最佳答案
Here是 spring mvc 引用。简单浏览了一下,发现了两种方法:
- @InitBinder
- @ModelAttribute("bean_name") 方法。
您可以使用 first 来自定义数据绑定(bind),从而即时创建命令对象。第二个允许您使用它注释方法并使用此名称预填充模型属性:
@ModelAttribute("bean_name")
public Collection<PetType> populatePetTypes() {
return this.clinic.getPetTypes();
}
我希望它会填充名为“bean_name”的模型属性(如果它为 null)。
关于Java - Spring 3.0 MVC 和@ModelAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8180574/