Issue
I am using longblob data type in a table to store image,At least, five images are stored, I want to retrieve all images from the database and want to display on jsp which consists of image tag, an image tag's attribute src is assigned to the servlet name as src="./Serv1", this Serv1 contains image retrieved from database but the problem is I have no idea how to show multiple images, It is showing only the first image, should I use loop if yes then how?
I have this in JSP page
while(r.next())
{
%>
<img src="./Serv1" height="100" width="200">
<p>Product <%=r.getInt(1)%>: <%=r.getString(2)%></p>
and my servlet whose url-pattern is Serv1 has this code
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();
Solution
Suppose you have jsp page where you want to retrieve image. You can do something like this to retrieve any image from database.
<% // 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){}
%>
In Above code this -> <img src="./Serv1?id=<%=resultSet.getString("id")%>" />
line is important ,here you are passing parameter
i.e : id
to servlet to get particular image
Now,in your servlet
i.e ./Serv1
you have to retrieve the id
in doGet
and pass in query ,lastly send back the reponse to jsp page .
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();
}
Also this is not complete code,make changes as per your requirements .also don't forget to add jar's file
Hope this helps!
Answered By - Swati