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)
The exception message is clear:
An
IOExceptionwas been thrown and you’re rethrowing it as a custom exception which forced the servletcontainer to show the exception page which will usegetWriter()for this. You should in fact let anyIOExceptiongo because that’s usually a point of no return.An
IOExceptioncan for example be thrown during the job when the client aborted the request. The best practice is to not catchIOExceptionon the Servlet API yourself. It’s already declared inthrowsclause of the servlet methods.