无法在空对象上获取 属性 'id'

Cannot get property 'id' on null object

我是 grails 的新手,正在开始自学。我正在尝试重现文档 upload/download 的示例。

我的域名Class:

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>

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

Error 500: Internal Server Error URI /demo2/document/list Class java.lang.NullPointerException Message Cannot get property 'id' on null object

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

你的 gsp 应该是

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

您想遍历列表中的项目,而不仅仅是打印单个项目。您收到 NPE 是因为当前页面上没有 DocumentInstance 变量(如上面的评论所述)。