代码之家  ›  专栏  ›  技术社区  ›  MBJH

结果集。next()未迭代

  •  -1
  • MBJH  · 技术社区  · 7 年前

    我的代码:

    public class DisplayImage extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String connectionURL = "jdbc:mysql://localhost:3306/ycards";
            java.sql.Connection con = null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection(connectionURL, "root", "letmein");
                PreparedStatement st1 = con.prepareStatement("select image from pictures");
                ResultSet rs1 = st1.executeQuery();
                String imgLen = "";
                while (rs1.next()) {
                    imgLen = rs1.getString(1);
                    int len = imgLen.length();
                    byte[] rb = new byte[len];
                    InputStream readImg = rs1.getBinaryStream(1);
                    readImg.read(rb, 0, len);
                    response.setContentType("image/png");
                    response.getOutputStream().write(rb, 0, len);
                    response.getOutputStream().flush();
                }
                st1.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    }
    

    输出: enter image description here

    它只显示第一行,不显示其余的,为什么要这样做?注意:在本例中,密码和用户名不是真实的。

    1 回复  |  直到 7 年前
        1
  •  2
  •   davidxxx    7 年前

    您正在迭代 ResultSet next() 将光标从当前位置向前移动一行,然后返回 false 读取最后一个位置时。

    问题是您正在刷新 httpResponse.outputstream 在每次迭代中。
    和呼叫 flush() PrintWriter 提交HTTP响应。
    因此,在第一次迭代之后,您无法编写任何内容。

    我认为您无法发送具有图像内容类型的多幅图像:

    response.setContentType("image/png");
    

    如果您想使用这种内容类型,也可以创建一个将所有内容组合在一起的大图像。
    但这真的有意义吗?

    我怀疑您不需要使用:

    回答setContentType(“图像/png”);
    

    但是,您应该使用应该首先生成的图像URL在客户端页面中显示图像。
    然后,可以使用JSTL或scriplet对url图像进行迭代,以将其呈现为HTML img 元素。