客户端中止时,ServletOutputStream不会抛出异常

时间:2015-01-08 11:17:25

标签: tomcat7

您好我的Tomcat-Webapp

中有以下构造
ServletOutputStream out = response.getOutputStream();
final PrintStream p = new PrintStream(out, true, "UTF-8");
while (condition) {
    p.println(StringUtils.join(values, ","));
    logger.debug("Exported line");
}

但是当我关闭请求浏览器时,代码会继续结束,即使需要几分钟并写入几兆字节。

我希望当客户端断开连接并且代码尝试将数据写入其中时,ServletOutputStream会抛出异常。

ServletOutputStream是

org.springframework.security.web.context.SaveContextOnUpdateOrErrorResponseWrapper$SaveContextServletOutputStream[delegate=org.apache.catalina.connector.CoyoteOutputStream@7fcdb6bc]

1 个答案:

答案 0 :(得分:0)

好吧,事实证明PrintStream涵盖了潜在的异常:

public void write(byte buf[], int off, int len) {
    try {
        synchronized (this) {
            ensureOpen();
            out.write(buf, off, len);
            if (autoFlush)
                out.flush();
        }
    }
    catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    }
    catch (IOException x) {
        trouble = true;
    }
}

所以我必须通过调用

手动检查错误
p.checkError()