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

时间:2019-02-05 06:40:16

标签: 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消息无法在enter image description here空对象上获取属性'id'

如何纠正此错误。请帮助我。

1 个答案:

答案 0 :(得分:1)

您的gsp应该是

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

您要遍历列表中的项目,而不仅仅是打印单个项目。您正在获得NPE,因为该页面上目前没有DocumentInstance变量(如上面的评论所述)。