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”

Answer

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.