我需要对 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 方法上?
提前感谢您的帮助
斯特凡诺