Java 在servlet中处理意外的结束请求
我目前正在用Jersey/Tomcat开发一个restweb服务(但欢迎使用通用Servlet/Container)。 如果客户端对返回大量数据的服务执行一些GET请求,则从MySQL连接获取 为了避免任何OOM异常,我使用MySQL的流模式 但是,如果客户端在加载期间中止请求,则MySQL连接不会关闭。 之后,服务器将不会处理任何其他请求,因为一次只能处理一个“流”请求 所以问题是:当请求在我的服务器上结束时(正常或异常),如何通知我。我能注册一些听众吗?或者使用未捕获的ExceptionHandler 我在Jersey中看到了许多处理异常以将其转换为“响应”的方法,但没有看到处理请求过早结束的方法。我猜Jersey或Tomcat可能会在没有通知的情况下销毁我的线程。我能在方法的关键部分捕捉到一些异常,以便知道何时发生这样的线程中断吗 提前感谢您的帮助Java 在servlet中处理意外的结束请求,java,exception,servlets,jdbc,thread-abort,Java,Exception,Servlets,Jdbc,Thread Abort,我目前正在用Jersey/Tomcat开发一个restweb服务(但欢迎使用通用Servlet/Container)。 如果客户端对返回大量数据的服务执行一些GET请求,则从MySQL连接获取 为了避免任何OOM异常,我使用MySQL的流模式 但是,如果客户端在加载期间中止请求,则MySQL连接不会关闭。 之后,服务器将不会处理任何其他请求,因为一次只能处理一个“流”请求 所以问题是:当请求在我的服务器上结束时(正常或异常),如何通知我。我能注册一些听众吗?或者使用未捕获的ExceptionHa
Raphael通常,只要对
响应调用flush()
或close()
时,就会抛出IOException
,而另一端已中止连接
通常,关闭数据库连接(和其他资源)应该发生在打开数据库连接的try
块的finally
块中,以便在异常情况下仍然关闭数据库连接
综上所述,此示例应做到:
String search = getItSomehow();
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = database.getConnection();
statement = connection.prepareStatement(SQL_FIND);
statement.setString(1, search);
resultSet = statement.executeQuery();
if (resultSet.next()) {
response.setContentType(resultSet.getString("contentType"));
response.setContentLength(resultSet.getInt("contentLength")); // Optional.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(resultSet.getBinaryStream("content"));
output = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
for (int length; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
output.flush();
}
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
} catch (SQLException e) {
throw new ServletException("Something failed at SQL/DB level.", e);
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
无需关闭输出流-servlet将为您完成此操作。另外,如果您使用的是PrintWriter,请使用checkError而不是flush。@andrew: