Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa JSP-Servlet how to retrieve images from database to jsp?
Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


divya
how to retrieve images from database to jsp?
1 Answer(s)      2 years and 8 months ago
Posted in : JSP-Servlet


Hi sir,i want to stores images along with the name and price with database and retrieve it on jsp.and that image also should act as link.when i click on the image retrieved,it should display the elaborated image in th next page.plz help me in coding.its vey urgent.


Advertisement
View Answers

April 9, 2012 at 1:04 PM


1)images:

<%@ page import="java.sql.*,java.io.*,java.util.*" %> 
<HTML>
 <table border="1">
 <tr><th>ID</th><th>Image</th></tr>
   <%
  try{      
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
    Statement stmt=con.createStatement();
    String strQuery = "select * from data";
    ResultSet rs = stmt.executeQuery(strQuery);
    while(rs.next()){
       %>
      <tr>
      <td><%=rs.getInt("id")%></td>
      <td>
      <img src="image.jsp?imgid=<%=rs.getInt(1)%>" width="100" height="100">
</a></td>
      </tr>
      <%
    }
    rs.close();
    con.close();
    stmt.close();
  }
  catch(Exception e)
  {
    e.getMessage();
  }
  %>
 </table>
</HTML>

2)image.jsp:

<%@ page import="java.sql.*,java.io.*,java.util.*" %> 
<%
  int id =  Integer.parseInt(request.getParameter("imgid"));
  try{      
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");      
    Statement st=con.createStatement();
    String strQuery = "select image from data where id="+id;
    ResultSet rs = st.executeQuery(strQuery);

    String imgLen="";
    if(rs.next()){
      imgLen = rs.getString(1);
       }  
    rs = st.executeQuery(strQuery);
    if(rs.next()){
      int len = imgLen.length();
      byte [] rb = new byte[len];
      InputStream readImg = rs.getBinaryStream(1);
      int index=readImg.read(rb, 0, len);  
      st.close();
      response.reset();
      response.getOutputStream().write(rb,0,len); 
      response.getOutputStream().flush();        
    }
  }
  catch (Exception e){
    e.printStackTrace();
  }
%>


Related Tutorials/Questions & Answers:
Advertisements
 

 

 

DMCA.com