gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:17:03 25 4
gpt4 key购买 nike

我是新手,自己开始学习。我正在尝试重现文档上载/下载的示例。

我的网域类别:

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 enter image description herenull object



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

最佳答案

您的gsp应该是

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

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

关于grails - 无法在空对象上获取属性 'id',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54528945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com