ResultSet.next() 不迭代
ResultSet.next() not iterating
我的代码:
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();
}
}
}
输出:
它只显示第一行,其余的不显示,这是为什么?注意:为了这个例子,密码和用户名不是真实的。
您正在 ResultSet
上迭代,因为 next()
将光标从当前位置向前移动一行,return false
是读取最后一个位置。
问题是您在每次迭代时都刷新 httpResponse.outputstream
。
在 PrintWriter
上调用 flush()
提交 HTTP 响应。
所以你不能在第一次迭代后写任何东西。
我认为您不能发送多个图像内容类型的图像:
response.setContentType("image/png");
如果您想使用此内容类型,您可以创建一个包含所有内容类型的大图像。
但这真的有意义吗?
我怀疑你不需要使用 :
response.setContentType("image/png");
但是您应该使用您应该首先生成的图像 url 在客户端页面中显示图像。
然后您可以使用 JSTL 或 scriplet 迭代 url 图像以将它们呈现为 HTML img
元素。
我的代码:
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();
}
}
}
输出:
它只显示第一行,其余的不显示,这是为什么?注意:为了这个例子,密码和用户名不是真实的。
您正在 ResultSet
上迭代,因为 next()
将光标从当前位置向前移动一行,return false
是读取最后一个位置。
问题是您在每次迭代时都刷新 httpResponse.outputstream
。
在 PrintWriter
上调用 flush()
提交 HTTP 响应。
所以你不能在第一次迭代后写任何东西。
我认为您不能发送多个图像内容类型的图像:
response.setContentType("image/png");
如果您想使用此内容类型,您可以创建一个包含所有内容类型的大图像。
但这真的有意义吗?
我怀疑你不需要使用 :
response.setContentType("image/png");
但是您应该使用您应该首先生成的图像 url 在客户端页面中显示图像。
然后您可以使用 JSTL 或 scriplet 迭代 url 图像以将它们呈现为 HTML img
元素。