【发布时间】:2021-07-01 22:58:25
【问题描述】:
我正在尝试使用 for 循环从数据库中检索多个图像,其中数据库存储了 4 个不同的图像,ID 列中的 ID 号从 1 到 4。我已经使用会话来传递 for 循环的每个递增值(为每个选择元素选项检索所有 4 个图像),但只有 ID=4 的最后一个图像显示在选择元素的所有 4 个选项中。
请找到数据库图像。
jsp页面
<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>
/下载图片页面
@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
【问题讨论】: