我在Grails应用程序中使用opencsv将属性从Person域类导出到CSV。但是,我收到以下错误:
Servlet.service()for servlet [default]在上下文中,路径[/ myapp]引发异常[请求处理失败;嵌套异常是org.codehaus.groovy.grails.web.pages.exceptions.GroovyPagesException:处理GroovyPageView时出错:已根据原因调用了此响应的getOutputStream() 消息:已为此响应调用了getOutputStream()
从在线搜索,我认为答案可能是在某处为HttpServletResponse响应实现一些responseComplete()方法。但是,我不知道该怎么做。有任何想法吗?这是我的代码:
def export = {
def course = Course.get(params.id)
if(course){
def persons = course ? Person.findAllByCourse(course) : []
response.setHeader("Content-disposition",
"attachment; filename=people.csv")
response.contentType = "text/csv"
def out = response.outputStream
out.withWriter { writer ->
String[] properties = new String[3]
def csvWriter = new CSVWriter(writer)
persons.each { person ->
properties[0] = person.firstName
properties[1] = person.lastName
properties[2] = person.email
properties[3] = person.phone
properties[4] = person.address1
properties[5] = person.address2
properties[6] = person.city
properties[7] = person.state
properties[8] = person.zip5
csvWriter.writeNext(properties)
}
csvWriter.flush()
}
}
答案 0 :(得分:1)
您的问题可能源于显式写入控制器中的输出流,然后是从操作返回时GSP呈现的默认行为。您可以通过几个修复程序检查How to prevent Grails from rendering the default view?以查找其他案例。我目前在机器上没有grails重新创建问题,但听起来像在关闭结束时添加显式return null
可能有所帮助。或者通过render
生成一些令牌输出或200状态代码。
答案 1 :(得分:0)
你必须通过String [] properties = new String [9]更改此proprity String [] properties = new String [3]。
它对我有用。