如何从数据库中检索图像并放在JSP上?

jan*_*nik 1 java jsp servlets jdbc

我有一个JSP页面,它应该从数据库中获取所有图像,并且应该在一个表上显示.我的结果集对象'rs'指向图像.我的代码是这样的:

String query = "select image from stock";
rst = stmt.executeQuery(query);
while(rst.next())
<%
<td><img height="89" src=<%rst.getString(1)%></td>
%>
  }
Run Code Online (Sandbox Code Playgroud)

我知道,getString不适用于BLOB类型.我甚至使用了getBinaryStream(),但没有成功.任何的想法?

Moh*_*igh 5

使用以下代码将Blob转换为byte []:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
InputStream in = blob.getBinaryStream();
int n = 0;
while ((n=in.read(buf))>=0)
{
   baos.write(buf, 0, n);
}
in.close();
byte[] bytes = baos.toByteArray(); 
Run Code Online (Sandbox Code Playgroud)

使用Servlet编写图像:

if (bytes != null && bytes.length > 0) {
 response.setContentType("image/jpg");
 response.getOutputStream().write(bytes);
 response.getOutputStream().flush();
 response.getOutputStream().close();
}
Run Code Online (Sandbox Code Playgroud)

使用jsp中的servlet请求URL来反转您的图像:

<img src="imageDisplayProcess.do?pKey=imageId" width="117" height="160"
 onError="loadImage()" onAbort="loadImage()" />

imageDisplayProcess.do?pKey=imageId //should be your image servlet URL
Run Code Online (Sandbox Code Playgroud)