Java-Spring 3.0 MVC和@ModelAttribute
作者:互联网
我需要一些有关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方法上?
预先感谢您的帮助
斯特凡诺
解决方法:
Here是Spring MVC参考.简要浏览一下,发现了两种方法:
> @InitBinder
> @ModelAttribute(“ bean_name”)与方法.
您可以先使用自定义数据绑定,然后动态创建命令对象. Second允许您使用它来注释方法,并使用以下名称预填充模型属性:
@ModelAttribute("bean_name")
public Collection<PetType> populatePetTypes() {
return this.clinic.getPetTypes();
}
我希望它可以将名称为“ bean_name”的模型属性填充为空.
标签:modelattribute,java,spring-mvc 来源: https://codeday.me/bug/20191202/2085700.html