You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JSP中通过Servlet显示数据库中的多张LongBlob图片?

哦,这个问题我太熟了!你现在只显示第一张图片的原因很明确——你的Servlet每次被请求时,都会去查整个product表,然后只返回第一条记录的图片,所有<img>标签都请求同一个Serv1,自然都拿到同一张图。而且你确实需要循环,但不是在Servlet里循环,而是要让每个<img>标签告诉Servlet“我要哪张图”,然后Servlet按需返回对应的图片。

第一步:修改JSP页面,给每个img传递产品ID参数

你的JSP里已经在循环ResultSet,而且能拿到产品ID(r.getInt(1)),那就在<img>的src里带上这个ID,让Servlet知道要返回哪个产品的图片:

<%
// 假设你的ResultSet r是从查询product表(包含id、name、prodimg等字段)来的
while(r.next()) { 
%>
  <img src="./Serv1?id=<%=r.getInt(1)%>" height="100" width="200">
  <p>Product <%=r.getInt(1)%>: <%=r.getString(2)%></p>
<%
}
%>

这里的id=<%=r.getInt(1)%>是关键,每个<img>请求都会带上对应产品的ID,Servlet就能根据这个ID找到对应的图片。

第二步:修改Servlet代码,根据请求参数返回对应图片

原来的Servlet逻辑是查所有图片然后只取第一张,现在要改成根据传入的ID查询单张图片,还要注意用PreparedStatement防止SQL注入,同时正确处理资源关闭:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 获取请求里的产品ID
    String productIdStr = request.getParameter("id");
    if (productIdStr == null || productIdStr.isEmpty()) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing product ID");
        return;
    }
    int productId = Integer.parseInt(productIdStr);

    Connection con = null;
    PreparedStatement pst = null;
    ResultSet r = null;
    OutputStream oos = null;
    try {
        // 假设你已经有获取数据库连接的方法,比如getConnection()
        con = getConnection();
        // 用PreparedStatement防止SQL注入
        String sql = "select prodimg from product where id = ?";
        pst = con.prepareStatement(sql);
        pst.setInt(1, productId);
        r = pst.executeQuery();

        if (r.next()) {
            Blob img = r.getBlob(1);
            byte[] imgbyte = img.getBytes(1, (int) img.length());
            response.setContentType("image/jpg");
            oos = response.getOutputStream();
            oos.write(imgbyte);
            oos.flush();
        } else {
            // 如果没有找到对应ID的图片,返回404错误
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "Product image not found");
        }
    } catch (SQLException e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database error");
    } finally {
        // 依次关闭资源,避免资源泄漏
        try { if (r != null) r.close(); } catch (SQLException e) {}
        try { if (pst != null) pst.close(); } catch (SQLException e) {}
        try { if (con != null) con.close(); } catch (SQLException e) {}
        try { if (oos != null) oos.close(); } catch (IOException e) {}
    }
}

这里要注意几个细节:

  • 用request.getParameter("id")拿到JSP传过来的产品ID,做非空校验
  • 用PreparedStatement代替Statement,把ID作为参数传入,彻底避免SQL注入风险
  • 在finally块里关闭所有数据库资源和输出流,防止资源泄漏
  • 处理找不到图片的情况,返回404错误提示

为什么原来的方法不行?

你之前的Servlet每次被请求都会执行select prodimg from product;,然后只取第一条记录(if(r.next())),所以不管哪个<img>请求,返回的都是第一张图。现在每个<img>请求都带了不同的ID,Servlet根据ID查询对应图片,就能正确显示每张图了。

内容的提问来源于stack exchange,提问作者Arhana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:24:16