我需要一些关于Spring 3.0 MVC和@ModelAttribute注释方法参数的说明。我有一个控制器,它看起来像这样的:Java - 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的
<form:form action="home" commandName="barCommband">
</form:form
的RequestMethod.POST方法现在形式如果我尝试访问回到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方法上?
在此先感谢您的帮助
斯特凡诺