【问题标题】:HttpSession attribute : getAttribute() only passing/getting last value in the loop [duplicate]HttpSession属性:getAttribute()仅传递/获取循环中的最后一个值[重复]
【发布时间】: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

【问题讨论】:

    标签: java jsp servlets


    【解决方案1】:

    要完成这项工作,您需要将图像的 id 放入用作 img 标记来源的 URL。
    src="./DownloadImage?Id=1" 然后,您可以使用访问端点中的 id req.getParameter("Id");

    【讨论】:

      猜你喜欢
      • 2017-08-19
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      • 2016-01-31
      • 2021-09-15
      • 2016-03-03
      相关资源
      最近更新 更多