我有一个jsp其中表中的每一行我需要显示数据库中存在的图像。我从数据库中检索所有表格行数据,包括图像作为Blob,并将其存储在一个bean中。该图像被存储在bean作为字节数组这样的:图像没有送达jsp从Servlets
photo = rs.getBlob("PHOTO");
photoByteArray = photo.getBytes(1, (int)photo.length());
虽然循环遍历JSP豆的列表中,在src属性指向这样一个servlet:
<img class="img" width="55" height="50" src="displayThumbnail?photoData=${part.photoData}">
供应的图像如下所示,但是它们不显示,但是在调试字节数组时似乎有数据。
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg");
OutputStream o = response.getOutputStream();
String photoDataStr = request.getParameter("photoData");
byte[] photoData = null;
if(photoDataStr != null) {
photoData = photoDataStr.getBytes();
}
o.write(photoData);
o.close();
}
但是图像没有显示出来。现在,如果我如下所示查询每个单独图像的数据库,那么在这种情况下图像确实显示得很好。
protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
PreparedStatement pstmt = null;
ResultSet rs = null;
Connection conn = null;
try {
if(conn == null) {
conn = open();
}
pstmt = conn.prepareStatement("select photo from PART_PHOTOS where id = ?");
String id = request.getParameter("id");
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
Blob b = rs.getBlob("photo");
response.setContentType("image/jpeg");
response.setContentLength((int) b.length());
InputStream is = b.getBinaryStream();
OutputStream os = response.getOutputStream();
byte buf[] = new byte[(int) b.length()];
is.read(buf);
os.write(buf);
os.close();
is.close();
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
pstmt = null;
}
//check if it's the end of the loop
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
我非常感谢,如果任何人都可以提供任何相同的建议。
@BaluC:有没有什么快速的方法不需要花费太多的时间来设置缓存等等。 – 2011-04-22 16:24:40
@BalusC:现在你应该可以从OP留下的一些其他评论中看到,他的确是,试图将图像数据直接粘贴到HTML:quote中,“$ {part.photoData}返回从初始数据库调用中检索到的字节数组”。然后他希望他的servlet能够从嵌入它的地方提取该字节数组作为标记中的URL,并将其直接返回给请求者。我认为我对我的解释非常清楚,但其他答复似乎都没有意识到发生了什么。 – 2011-04-22 17:21:59
哦,他试图通过整个图像作为参数!对不起,我现在看到了。我将它解释为图像标识符。我回我的话。 – BalusC 2011-04-22 17:28:50