如果在响应对象的OutputStream打开后发生异常,则Tomcat容器无法使用<error-page>配置

Cod*_*lue 5 java spring containers tomcat java-ee

我正在使用Tomcat 5.5和Spring 3.2.在web.xml部署描述符中,我有以下配置 -

  <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>
Run Code Online (Sandbox Code Playgroud)

无法解释的行为发生在类似于下面的方法中 -

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
 }
Run Code Online (Sandbox Code Playgroud)

当发生FileNotFoundException时,我没有看到我的自定义500.jsp用于呈现错误页面,而是在页面上看到了异常的整个堆栈跟踪.如果我只是颠倒两个语句的顺序如下,

    InputStream stream = new FileInputStream(file); // FileNotFoundException here
    OutputStream out = response.getOutputStream();
Run Code Online (Sandbox Code Playgroud)

一切正常,我得到了正确的500.jsp在页面上呈现.

为什么会这样?唯一的区别是在后一种情况下,响应对象的OutputStream未打开.

ser*_*.vi -1

我认为您需要添加自定义控制器来渲染web.xml.

@参见此处的描述:Tomcat with Spring 中的自定义错误页面