HttpSession属性:getAttribute()只传递/获取循环中的最后一个值



我正试图使用for循环从数据库中检索多个图像,其中数据库存储有ID列中ID号从1到4的4个不同图像。我已经使用会话来传递for循环的每个递增值(为每个select元素选项检索所有4个图像(,但只有ID=4的最后一个图像显示在select元素的所有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();
}
}
}

数据库映像数据库图像

要实现这一点,您需要将图像的id放入用作img标记源的URL中
src="下载图像?Id=1";然后,您可以使用访问端点中的idreq.getParameter("Id"(;