Spring模型 - “模型对象不能为空”

时间:2014-08-21 18:56:47

标签: spring-mvc spring-4

我的一个Spring控制器类中的方法

@RequestMapping(value = "/products/{productId}/specifications", method = RequestMethod.GET)
public String setup(@PathVariable("productId") Integer pid, Model m) {
  //... 
  m.addAttribute(foo);  <-- error
  return "my-page";
}

收到错误消息“Model对象不能为null”后,我更改了方法签名,如下所示:         public ModelAndView setup(@PathVariable(“productId”)Integer pid){

    //...
    ModelAndView mv = new ModelAndView("my-page");
    mv.addObject(foo);     <-- error

    return mv; 
}

我能够运行修改过的代码一次。但是我在ModelAndView上遇到了同样的错误。我使用Spring MVC多年了。这是我第一次遇到这个问题。原因是什么?

我使用Spring 4.0.6.RELEASE。

1 个答案:

答案 0 :(得分:0)

虽然您没有提供显示foo引用所指向的代码,但可以安全地假设它是一个空引用。

我看了一下Github上的Project代码,很清楚这里发生了什么。

ModelAndView#addObject(Object)方法委托ModelMap#addAttribute(Object)方法,该方法使用您的问题所询问的确切消息断言所提供的Object不为空。

ModelAndView方法:

public ModelAndView addObject(Object attributeValue) {
    getModelMap().addAttribute(attributeValue);
    return this;
}

ModelMap方法:

public ModelMap addAttribute(Object attributeValue) {
    Assert.notNull(attributeValue, "Model object must not be null");
    if (attributeValue instanceof Collection && ((Collection<?>) attributeValue).isEmpty()) {
        return this;
    }
    return addAttribute(Conventions.getVariableName(attributeValue), attributeValue);
}
相关问题