0

I am using opencsv in my Grails application to export attributes from my Person domain class to CSV. I am receiving the following error, however:

Servlet.service() for servlet [default] in context with path [/myapp] threw exception [Request processing failed; nested exception is org.codehaus.groovy.grails.web.pages.exceptions.GroovyPagesException: Error processing GroovyPageView: getOutputStream() has already been called for this response] with root cause Message: getOutputStream() has already been called for this response

From searching online, I think the answer may be to implement some responseComplete() method somewhere for the HttpServletResponse response. However, I am not sure how to do this. Any ideas? Here is my code:

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

    }
littleK
  • 19,521
  • 30
  • 128
  • 188
  • Have you got a `render` or `redirect` being called anywhere (that's outside the above code)? – Jon Burgess Nov 02 '12 at 02:43
  • Try to use the gsp template for the CSV and standard model filled with data. – Tom Metz Nov 02 '12 at 08:12
  • As I am a bit new to Grails, I am not sure what you're referring to when you say the gso template for CSV. Can you elaborate a bit or point to an example? Thanks! – littleK Nov 02 '12 at 11:38

2 Answers2

1

Your problem probably stems from explicitly writing to the output stream in your controller, followed by the default behavior of GSP rendering upon returning from your action. You might check How to prevent Grails from rendering the default view? for another case of this, with a couple fixes. I don't have grails on the machine I'm on currently to recreate the issue, but sounds like adding an explicit return null to at the end of the closure may help. Or producing some token output or a 200 status code via render.

Community
  • 1
  • 1
Brian Henry
  • 3,161
  • 1
  • 16
  • 17
0

You have to change this proprity String[] properties = new String[3] by String[] properties = new String[9].

It works for me.

user2068981
  • 298
  • 1
  • 3
  • 6