我在表中使用longblob数据类型存储图像,至少存储了五张图像,我想从数据库中检索所有图像,并想在包含图像标签,图像标签的属性src的jsp上显示被指定为src =“ ./ Serv1”的servlet名称,此Serv1包含从数据库检索到的图像,但问题是我不知道如何显示多个图像,它仅显示第一个图像,如果是,我应该使用循环那怎么办
我在JSP页面中有这个
while(r.next())
{
%>
<img src="./Serv1" height="100" width="200">
<p>Product <%=r.getInt(1)%>: <%=r.getString(2)%></p>
我的url模式为Serv1的servlet具有此代码
ResultSet r=st.executeQuery("select prodimg from product;");
if(r.next()){
img= r.getBlob(1);
imgbyte=img.getBytes(1, (int)img.length());
response.setContentType("image/jpg");
oos=response.getOutputStream();
}
oos.write(imgbyte);
con.close();
答案 0 :(得分:0)
假设您有要检索图像的jsp页面。您可以执行类似的操作以从数据库中检索任何图像。
<% // dbconnection
try {
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","");
Statement statement = conn.createStatement() ;
resultSet=statement.executeQuery("select * from product") ;
%>
<!--this loop will get all images-->
<% while(resultSet.next()){ %>
<!--I'm using id column of table,you can use any coulmn which is unique to all row-->
Image - <img src="./Serv1?id=<%=resultSet.getString("id")%>" width="20%"/>
< p>Product <%=r.getInt(1)%>: <%=r.getString(2)%></p>
<%
}
}catch(Exception e){}
%>
在上面的代码中,此-> <img src="./Serv1?id=<%=resultSet.getString("id")%>" />
行很重要,这里您将parameter
传递给servlet,以获取特定的id
现在,在image
即servlet
中,您必须在./Serv1
中检索id
并传递查询,最后将响应发送回jsp页面。
doGet
这也不是完整的代码,请根据您的要求进行更改。也不要忘记添加Blob image = null;
byte[] imgData = null;
String id= request.getParameter("id");//here you are getting id
int i;
ResultSet rs =null;
try {
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","");
String sql = "SELECT prodimg FROM product where id=?"; //here pass that id in query to get particular image
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, id);
rs = ps.executeQuery();
while (rs.next()) {
image = rs.getBlob("image");//getting image from database
imgData = image.getBytes(1,(int)image.length()); //extra info about image
}
response.setContentType("image/gif");//setting response type
OutputStream o = response.getOutputStream();
o.write(imgData);//sending the image to jsp page
o.flush();
o.close();
}
catch(Exception e)
{
e.printStackTrace();
}
希望这会有所帮助!