简体   繁体   中英

ResultSet.next() not iterating

My code:

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();
        }

    }
}

Output: 在此处输入图片说明

It only displays the first row, not the rest, why does it do this? Note: password and username are not real for the sake of this example.

You are iterating on the ResultSet as next() moves the cursor froward one row from its current position and return false as the last position was read.

The problem is you are flushing the httpResponse.outputstream at each iteration.
And calling flush() on the PrintWriter commits the HTTP response.
So you cannot write anything after the first iteration.

I don't think that you can send multiples images with a image content type :

response.setContentType("image/png");

As alternative if you want to use this content type, you could create a big image that combines all of them.
But does it make really sense ?

I suspect that you don't need to use :

response.setContentType("image/png");

But you should display the images in the client page by using the image urls that you should generate first.
Then you can use JSTL or scriplet to iterate on the url images to render them as HTML img elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM