Anony dev
Anony dev

Reputation: 13

Servlet error: Cannot call sendRedirect() after the response has been committed

I want to redirect to a page after writing the excel file. The servlet code is given below:

ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
        workbook.write(outByteStream);
byte [] outArray = outByteStream.toByteArray();
        response.setContentType("application/ms-excel");
        response.setContentLength(outArray.length);
        response.setHeader("Content-Disposition", "attachment; filename=name_"+date+".xlsx");
        response.setIntHeader("Refresh", 1);
        OutputStream outStream = response.getOutputStream();
        outStream.write(outArray);
        response.sendRedirect("url/reports.jsp");

This code downloads an Excel file which i have created. when i call the above servlet, the excel file is being downloaded but it is throwing following exception in the last line :

Servlet Error: ::java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

Hence i am unable to redirect to a new page. what can i do to access the response object after i write the output in "outStream"

Upvotes: 0

Views: 1173

Answers (2)

Maurice Perry
Maurice Perry

Reputation: 9651

You cannot have a body with a redirect because the browser, when receiving a redirect, will issue a second request to the URL it has found (in header Location), and it's the response of that second request that is displayed, unless it is also a redirect, in which case, it will issue a third request, and so on...

Upvotes: 0

John Bollinger
John Bollinger

Reputation: 180048

The basic problem is that this ...

I want to redirect to a page after writing the excel file.

... describes two separate responses. The server cannot chain them together by itself because the client will expect only one response to each request. Because two requests are required to elicit two responses, automation of this sequence will require client-side scripting.

Personally, I would probably put the script on the front end: a handler on the appropriate button or link that first downloads the file and then (on success) issues a request for the new page. It would also be possible to do as suggested in comments, however: put script in the new page that downloads the file.

Upvotes: 2

Related Questions