Grails 无法获取属性';id';关于空对象

Grails 无法获取属性';id';关于空对象,grails,Grails,我对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) }} 我的Doc

我对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()
}
}


}
我的名单是普惠制

<g:link action="download" id="${DocumentInstance.id}"> ${fieldValue(bean: DocumentInstance, field: "fileName")}</g:link>
${fieldValue(bean:DocumentInstance,field:“fileName”)}
但是,当我运行应用程序时,我得到以下错误:

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

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

您的普惠制应该是

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

${DocumentInstance.fileName}

您希望迭代列表中的项目,而不仅仅是打印单个项目。您获得NPE是因为页面上当前没有
DocumentInstance
变量(如上面的注释所示)。

从您的代码中,我可以看到您在
upload()
操作中声明了
DocumentInstance
,但在
列表()中没有声明,你说gsp是
list.gsp
,它指的是
list()
,如果你想避免NPE,那就添加?类似这样的变量名:
${DocumentInstance?.id}
@bitsnaps。我应该在列表()中定义DocumentInstance吗。很抱歉,这是我正在处理的第一个grails应用程序。每个出现在操作中的实例变量都将出现在gsp页面中,这就是MVC框架的工作方式,不管怎样,都可以问:祝你好运。@bitsnaps谢谢你。我会按照你的建议改正的