【问题标题】:Display image (from database) in JSP [duplicate]在 JSP 中显示图像(来自数据库)[重复]
【发布时间】:2016-03-12 04:57:28
【问题描述】:

我想知道如何在 for 循环内的 JSP 页面中显示图像。图像是从数据库中访问的。下面是我的代码,我希望图像正好在"<img src="<%= product.thumbnail %>"/>" 所在的位置。

我的代码简短而简单:

<%
    for(int i=0; i<keys.length;i++){
        Product product = sdb.getProduct(keys[i].toString());
        out.println( "<p>" + product.title + "    " + "<img src="<%= product.thumbnail %>"/>" + "</p>" );
    }
%>

谢谢

--编辑后添加--

生成的 HTML:

<html>

<body>

<p>Linez    99.99    1</p>
<p>Stax    49.99    3</p>


<p> Order total = 249.96


<form action="order.jsp" method="post">
  <input type="text" name="name" size="20">
  <input type="submit" value="Place Order" />
</form>

<form action="basket.jsp" method="get">
  <input type="hidden" name="emptyBasket" value="yes">
  <input type="submit" value="Empty Basket" />
</form>

</body>
</html>

【问题讨论】:

  • product.thumbnail 是 URL 吗?当您说从数据库中获取图像时,它是 base64 表示还是 URL?您还可以发布此 JSP 生成的 HTML 吗?谢谢。
  • @Sid 刚刚添加了生成的 HTML,是的,这就是产品在数据库中保存图像的 URL
  • 我认为问题可能出在语法上。 &lt;% 似乎放错了地方。你能检查一下吗?此外,&lt;img&gt; 标签似乎根本没有生成。有什么例外吗?
  • 也不例外。我自己对此感到困惑
  • 尝试只使用一组&lt;% %&gt; 标签而不是嵌套它们。在开始另一个之前完成一个脚本标签。

标签: java jsp jsp-tags


【解决方案1】:

我认为您还需要做更多的工作才能实现这一目标。 img 标签需要一个 URL,并且不能神奇地将数据库 blob 或类似的 URL 转换为 URL。

我的做法是:

  • 创建一个 servlet,从数据库中提供缩略图图像,并发布诸如 /myApp/product/thumbnails?productId=12345 之类的 URL
  • 从浏览器测试您的 servlet
  • 更改您的 JSP 以创建这些 URL。

祝你好运。

【讨论】:

    【解决方案2】:

    您需要在代码中使用 InputStream,我向您保证这将完美运行。 在谷歌上搜索它的信息。

    1) a.jsp 页面

    <img src="image.jsp?imgid=<%=rs.getInt(1)%>" alt="<%= rs.getString("title")%>" style="width:280px; height:320px">
    

    2) 把下面的代码放到另一个jsp页面

    int id = Integer.parseInt(request.getParameter("imgid"));//imgid from a.jsp
    try {
    
        String strQuery = "select book_image from tblbooks where id=" + id;
        ResultSet rs = st.executeQuery(strQuery);
    
        String imgLen = "";
        if (rs.next()) {
            imgLen = rs.getString(1);
        }
        rs = st.executeQuery(strQuery);
        if (rs.next()) {
            int len = imgLen.length();
            byte[] rb = new byte[len];
            InputStream readImg = rs.getBinaryStream(1);
            int index = readImg.read(rb, 0, len);
            st.close();
            response.reset();
            response.getOutputStream().write(rb, 0, len);
            response.getOutputStream().flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-18
      • 2012-02-23
      • 1970-01-01
      • 2012-10-24
      • 2016-10-11
      • 2013-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多