Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tomcat container fails to use <error-page> configuration if exception occurs after the response object's OutputStream is opened

I'm using Tomcat 5.5 and Spring 3.2. In the web.xml deployment descriptor, I have the following configuration -

  <error-page>
    <error-code>500</error-code>
    <location>/500.jsp</location>
  </error-page>
  <error-page>
    <error-code>403</error-code>
    <location>/403.jsp</location>
  </error-page>
  <error-page>
    <error-code>404</error-code>
    <location>/404.jsp</location>
  </error-page>

The unexplained behavior occurs in a method similar to the one below -

public ModelAndView fileDownload(HttpServletRequest request, 
                                 HttpServletResponse response) throws Exception 
 {
    String filename = (String) request.getParameter("filename");  
    //...more code
    File file = new File(...+ filename); // pseudo code
    OutputStream out = response.getOutputStream();  
    InputStream stream = new FileInputStream(file); // FileNotFoundException here
    //...more code
 }

When a FileNotFoundException occurs, I don't see my custom 500.jsp used to render the error page, but instead I see the entire stack trace of the exception on the page. If I simply reverse the order of the two statements as below,

    InputStream stream = new FileInputStream(file); // FileNotFoundException here
    OutputStream out = response.getOutputStream();

everything works correctly and I get the correct 500.jsp rendered on the page.

Why does this occur? The only difference was that in the latter case, the OutputStream of the response object was not opened.

like image 714
CodeBlue Avatar asked Nov 27 '22 09:11

CodeBlue


1 Answers

Under the hood, the JSP is likely attempting to call the getWriter method on the HttpServletResponse. According to the spec, getWriter can be called or getOutputStream can be called, but not both. Since you have already called getOutputStream, the JSP is unable to write to the response.

http://docs.oracle.com/javaee/5/api/javax/servlet/ServletResponse.html#getOutputStream()

http://comments.gmane.org/gmane.comp.jakarta.tomcat.user/182025

like image 176
Benjamin Pack Avatar answered Nov 29 '22 04:11

Benjamin Pack