【问题标题】:Cannot get property 'id' on null object无法在空对象上获取属性“id”
【发布时间】:2019-02-06 22:44:05
【问题描述】:

我对 grails 很陌生,开始自学。我正在尝试重现文档上传/下载的示例。

我的领域类:

package demo2
class Document {
String filename
String type
String fullPath
Date uploadDate = new Date()
static constraints = {
filename(blank:false,nullable:false)
fullPath(blank:false,nullable:false)
}}

我的 DocumentController 是:

package demo2

class DocumentController {

def list()
{
params.max = 10
[DocumentInstanceList:Document.list(params),
DocumentInstanceTotal: Document.count()]
}

def index (Integer max)
{
redirect (action: "list", params:params)
}

def upload() { // upload a file and save it in a the        

file system defined inside the config file
def file = request.getFile('file')
if(file.empty) {
flash.message = "File cannot be empty"
} else {
def DocumentInstance = new Document()
DocumentInstance.filename = file.originalFilename
DocumentInstance.type = file.contentType
DocumentInstance.fullPath = grailsApplication.config.uploadFolder +file.originalFilename

file.transferTo(new File(DocumentInstance.fullPath))
DocumentInstance.save flush:true
}
redirect (action:'list')
}
def download(long id) { //download a file saved inside the file system
Document DocumentInstance = Document.get(id)
if ( DocumentInstance == null) {
flash.message = "Document not found."
redirect (action:'list')
} else {
response.setContentType("APPLICATION/OCTET-STREAM")
response.setHeader("Content-Disposition", "Attachment;Filename=\"${DocumentInstance.fileName}\"")

def file = new File(DocumentInstance.fullPath)
def fileInputStream = new FileInputStream(file)
def outputStream = response.getOutputStream()

byte[] buffer = new byte[4096];
int len;
while ((len = fileInputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}

outputStream.flush()
outputStream.close()
fileInputStream.close()
}
}


}

我的 list.gsp 是

<g:link action="download" id="${DocumentInstance.id}"> ${fieldValue(bean: DocumentInstance, field: "fileName")}</g:link>

但是当我运行应用程序时,我收到以下错误:

错误 500:内部服务器错误 URI /demo2/document/list 类 java.lang.NullPointerException 消息无法在null 对象上获取属性“id”

我该如何纠正这个错误。请帮助我。

【问题讨论】:

  • 从您的代码中,我可以看到您在 upload() 中声明了 DocumentInstance,但在 list() 操作中没有声明,并且您说 gsp 是 list.gsp,它指的是 @987654330 @,如果你想避免 NPE,只需添加 ?像这样的变量名:${DocumentInstance?.id}.
  • @bitsnaps。我应该在 list() 中定义 DocumentInstance。抱歉,这是我正在开发的第一个 grails 应用程序
  • 是的,每一个出现在动作中的实例变量都会在gsp页面中可用,这就是MVC框架的工作方式,不管怎样问都可以,祝你好运。
  • @bitsnaps 谢谢你。根据您的建议不正确

标签: grails


【解决方案1】:

你的 gsp 应该是

<g:each in="${DocumentInstanceList}" var="DocumentInstance">
  <g:link action="download" id="${DocumentInstance.id}"> ${DocumentInstance.fileName}</g:link> <br/>
</g:each>

您希望遍历列表中的项目,而不仅仅是打印单个项目。你得到一个 NPE 是因为页面上目前没有 DocumentInstance 变量(正如上面的评论所说)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    相关资源
    最近更新 更多