【问题标题】:Spring Model - "Model object must not be null"Spring Model - “模型对象不能为空”
【发布时间】:2014-10-15 12:51:52
【问题描述】:

我的 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";
}

收到错误消息“模型对象不得为空”后,我更改了方法签名,如下所示: 公共 ModelAndView setup(@PathVariable("productId") 整数 pid) {

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

    return mv; 
}

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

我使用 Spring 4.0.6.RELEASE。

【问题讨论】:

  • foo 引用是空引用吗?您的代码 sn-ps 没有显示 foo 引用所指向的内容。

标签: spring-mvc spring-4


【解决方案1】:

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

我在 Github 上查看了项目代码,很清楚这里发生了什么。

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 2012-03-18
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多