Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best practice response.getOutputStream

Tags:

java

servlets

any comments on my code on allowing user to download file.

if(fileObject !=null)
response.setHeader("Content-disposition", "attachment; filename=\""+fileObject.getFilename()+"\"");
response.setContentType(fileObject.getFiletype());
response.setContentLength((int)fileObject.getFilesize().intValue());
try {
 if(response !=null && response.getOutputStream() !=null &&fileObject!=null && fileObject.getBinData() !=null ){
    OutputStream out = response.getOutputStream();
    out.write(fileObject.getBinData());
 }


} catch (IOException e) {
    throw new ApplicationRuntimeException(e);
}

most of the time, i dont get below error. but once and a while, i get error

29 Nov 2010 10:50:41,925 WARN [http-2020-2] - Unable to present exception page: getOutputStream() has already been called for this response
java.lang.IllegalStateException: getOutputStream() has already been called for this response
 at org.apache.catalina.connector.Response.getWriter(Response.java:610)
like image 457
cometta Avatar asked Feb 26 '26 18:02

cometta


1 Answers

The exception message is clear:

Unable to present exception page: getOutputStream() has already been called for this response
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:610)

An IOException was been thrown and you're rethrowing it as a custom exception which forced the servletcontainer to show the exception page which will use getWriter() for this. You should in fact let any IOException go because that's usually a point of no return.

An IOException can for example be thrown during the job when the client aborted the request. The best practice is to not catch IOException on the Servlet API yourself. It's already declared in throws clause of the servlet methods.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    FileObject fileObject = getItSomehow();
    if (fileObject != null && fileObject.getBinData() != null) {
        response.setHeader("Content-disposition", "attachment; filename=\"" + fileObject.getFilename() + "\"");
        response.setContentType(fileObject.getFiletype());
        response.setContentLength((int)fileObject.getFilesize().intValue());
        response.getOutputStream().write(fileObject.getBinData());
    } else {
        // ???
    }
}
like image 79
BalusC Avatar answered Feb 28 '26 08:02

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!