Supponiamo che tu abbia una pagina JSP in cui vuoi recuperare le immagini. Puoi procedere così per recuperare qualsiasi immagine dal 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){} %>
Nel codice precedente questa riga è fondamentale:
<img src="./Serv1?id=<%=resultSet.getString("id")%>" />
qui passi il parametro, cioè id, alla servlet per ottenere la particolare immagine.
Ora, nella tua servlet (cioè ./Serv1) devi recuperare l'id nel doGet e passarlo nella query, infine rimandare la risposta alla pagina JSP.
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(); }
Anche questo non è codice completo: apporta le modifiche in base alle tue esigenze e non dimenticare di aggiungere i file jar.
Spero che sia d'aiuto!