1
votes

After doing some research online on the subject I currently managed to get things working with this code:

@RequestMapping(value = "/report040Generated", method = RequestMethod.GET)
    public String index(Model model, HttpServletResponse response, HttpServletRequest request) throws IOException {

        String myString = "Hello";
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition","attachment;filename=myFile.txt");
        ServletOutputStream out = response.getOutputStream();
        out.println(myString);
        out.flush();
        out.close();

        return "index";
    }

My proble is that when I click on my JSP button, the files gets downloaded but the method doesn't redirect to the "index" .jsp view and gives me an IllegalStateExcepton:

SEVERE: Servlet.service() for servlet jsp threw exception java.lang.IllegalStateException: getOutputStream() has already been called for this response

Any suggestions about what might be causing this issue ?

3

3 Answers

2
votes

It is not possible to redirect to another page when returning file as file itself is http response. Very good explanation is here: Spring - download file and redirect

0
votes

I think the logic in your program should be split in two parts, one for downloading and one for redirecting because once you write something to response # outputstream property, the response should be considered to be committed and should not be written to, for example with a url redirection.

Most web sites used to redirect first to a downloading page to get the file and then let the user click at some button/link to redirect back to any other page (index.jsp in this case).

In that downloading page you can do it with JS:

<script type="text/javascipt">
function startDownload()
{
var url='http://server.com/app/url?file=file.ext';  
window.open(url,'Download');
}
 
setTimeout("startDownload(), "2000"); // 2 seconds
</script>

Or try it through HTML:

<html>
<head>
<meta http-equiv="refresh" content=".;url=http://server.com/app/url?file=file.ext">
</head>
<body>
Downloading file.zip!
</body>
</html>
-1
votes

You need to first clear the default JSPWriter prior to return "index"

out.close(); out.clear(); //clears default JSPWriter return "index";