简体   繁体   中英

Display image (from database) in JSP

I would like to know how to display an image in a JSP page within a for loop. The image is accessed from a database. Below is my code and i'd like the image to be exactly where the line "<img src="<%= product.thumbnail %>"/>" is.

Short and simple chunk of my code:

<%
    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>" );
    }
%>

Thanks

--Added after edit--

Generated 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>

I think you have a little more work to do to get this going. The img<> tag expects a URL, and cannot magically convert a database blob or similar to a URL.

My approach would be:

  • Create a servlet that serves thumbnail images from the database, and publishes URLs like /myApp/product/thumbnails?productId=12345
  • Test your servlet from a browser
  • Change your JSP to create these URLs.

Good luck.

You need to use InputStream in your code i assure you this will work perfectly. for info search it on google it.

1) a.jsp page

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

2) Put following code another jsp page

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

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