Issue
I am trying to retrieve multiple images from database using for loop where database is stored with 4 different images having ID number from 1 to 4 in ID column. I have used sessions to pass every incremented value(to retrieve all 4 images for each select element option) of for loop but only the last image having ID=4 is getting displayed in all 4 options from select element.
Please find the database Image.
Jsp page
<div class="menu">
<form action="guestVenueDetails.jsp">
<select id="name" name="eventName" >
<option value="" selected disabled hidden>Select an Event</option>
<option value="IKEA">IKEA</option>
<option value="Nike">Nike</option>
<option value="Adidas">Adidas</option>
<option value="Puma">Puma</option>
</select>
</div>
<div class="content">
<%
for(int i =1; i<=4; i++){
session = request.getSession(true);
String id = ""+i;
session.setAttribute("eventSelection",id);
%>
<p class="image"><img src="./DownloadImage" alt=""></p>
<% } %>
</div>
</form>
/DownloadImage page
@WebServlet("/DownloadImage")
public class DownloadImage extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
HttpSession session = req.getSession(true);
String id = (String)session.getAttribute("eventSelection");
session.setAttribute("eventSelection", null);
session.removeAttribute("eventSelection");
byte[ ] img = null ;
ServletOutputStream sos = null;
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/event_booking","root","");
String sql="select image_field from images where id ="+id;
PreparedStatement ps= con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
img= rs.getBytes(1);
}
sos = resp.getOutputStream();
sos.write(img);
}catch(Exception e) {
e.printStackTrace();
}
}
}
Database Image Database Image
Solution
To make this work you need to put the id of the image into the URL used as the source of the img tag.
src="./DownloadImage?Id=1"
You can then access the id in your endpoint using
req.getParameter("Id");
Answered By - Deadron
Answer Checked By - David Marino (JavaFixing Volunteer)