通常、反対側が接続を中止している間に、またはが呼び出されるIOException
たびに がスローされます。flush()
close()
response.getOutputStream()
通常、DB 接続 (およびその他のリソース) のクローズは、例外が発生した場合でもクローズされるように、それがオープンされたfinally
ブロックのブロックで発生する必要があります。try
要約すると、この例は次のようにする必要があります。
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) {}
}