Java – best practice response getOutputStream

Allow users to download any comments about my code

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 will not be lower than mistakes But for a while, I got wrong

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)

Solution

The exception message is clear:

IOException is thrown and you re throw it as a custom exception, which forces servletcontainer to display the exception page that will use getwriter () In fact, you should let any IOException appear, because this is usually a no return path

For example, when a client aborts a request, an IOException can be thrown during a job The best practice is not to capture IOException on servlet API by yourself It is already declared in the throws clause of the servlet method

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 {
        // ???
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>