嘿,任何人都可以帮助我使用我的 servlet,该 servlet 旨在在从数据库中获取图像后将图像显示到我的 jsp 页面。我下面的图像 servlet 似乎根本没有在我的浏览器中显示图像,只有一个损坏的图像图标:
@WebServlet(name = "ImageServlet", urlPatterns = {"/Image"})
public class ImageServlet extends HttpServlet {
private DatabaseConnector dataManager;
BufferedInputStream input = null;
BufferedOutputStream output = null;
@Override
public void init() {
dataManager = new DatabaseConnector();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Prepare.
String name = request.getPathInfo().substring(1); // Returns "foo.gif". You may want to do nullchecks here to avoid NPE's.
ResultSet resultSet = null;
try {
// Query DB.
resultSet = dataManager.getPhotos(1);
if (resultSet.next()) {
// Image found, prepare response and send it.
response.setContentType(resultSet.getString("contentType"));
response.setContentLength(resultSet.getInt("contentLength"));
response.setHeader("Content-Disposition", "inline;filename=\"" + name + "\"");
input = null;
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)) > -1;) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) {
try {
output.close();
} catch (IOException logOrIgnore) {
}
}
if (input != null) {
try {
input.close();
} catch (IOException logOrIgnore) {
}
}
}
} else {
// No image found, send HTTP 404.
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(ImageServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(ImageServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException e) {
throw new ServletException("Something failed at SQL/DB level.", e);
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException logOrIgnore) {
}
}
}
}
}
我的 jsp 页面中的图像如下所示:
<img src="/Image/<%= h.getHomeID() %>">
最后,我的结果集来自的数据库连接器类是:
public ResultSet getPhotos(String photoID) throws
IllegalArgumentException, SQLException, ClassNotFoundException {
createConnection();
ResultSet rs = null;
PreparedStatement preparedStatement = null;
String strQuery = "SELECT home_photo.photo "
+ "FROM home_photo "
+ "WHERE home_photo.home_id = ?";
try {
preparedStatement = conn.prepareStatement(strQuery);
preparedStatement.setString(1, photoID);
rs = preparedStatement.executeQuery();
} catch (SQLException e) {
throw new SQLException(e);
} finally {
closeConnection();
return rs;
}
}
我的 web.xml 也是这样的:
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>DB.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/Image/*</url-pattern>
</servlet-mapping>
如果有人知道为什么没有显示图像,我将不胜感激