2011-11-18 72 views
3

我需要一些关于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方法上?

在此先感谢您的帮助

斯特凡诺

回答

3

Here是Spring MVC的参考。通过它看上去简要,发现2点的方法:

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

您可以使用第一个自定义数据绑定,因此,在即时创建命令对象。其次,您可以标注法,并用此名称预填充模型属性:

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

我希望这将填充名为“bean_name”模型属性,如果它是空的。