2

I have a JSP page where I am loading data from a database in a loop. One of the database columns holds images stored as Blob. I am able to load all data from the database successfully when I don't try to load the image column.

When I load all data inclusive of images, only one image shows up on the page and no other data is shown on the page. Why is that so. As you can see from code, I have 5 columns of strings and 1 column of Blob. I should be getting each of this for 5 rows. I am looking for a solution for loading images dynamically and not hard code image path.

<body>
<div class="container">
    <div class="row">
<%
    String dbURL = "jdbc:mysql://1.1.1.1:3306/db_name";
    String dbUser = "";
    String dbPass = "";
    Connection conn;   
try{
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        conn = DriverManager.getConnection(dbURL, dbUser, dbPass);

        Statement statement = conn.createStatement();
        ResultSet resultset =
                statement.executeQuery("select image, name, age, gender, contact, description from tablename");

        while(resultset.next()) {
            Blob bl = resultset.getBlob(1);
            byte[] pict = bl.getBytes(1,(int)bl.length());
            response.setContentType("image/jpg");
            OutputStream o = response.getOutputStream();   
%>

<div class="col-sm-4">
            <div class="k-cust_box">
                <h3><%= resultset.getString(2) %></h3>
                <hr>
                <img class="k-profile-img" src="<%o.write(pict);%>" height="100px" border="1" style="float: left; overflow: hidden" width="33%">
                <div class="k-driver-inner-box">
                    <h5>Age: <%= resultset.getString(3) %></h5>
                    <h5>Gender: <%= resultset.getString(4) %></h5>
                    <h5>Contact: <%= resultset.getString(5) %></h5>
                </div>
                <h5 class="k-fl-lt"><%= resultset.getString(6) %></h5>
            </div>
        </div>
<%}

}catch (Exception e){
    e.printStackTrace();
}

%>
        </div>
    </div>
</body> 
JasSy
  • 583
  • 5
  • 17
  • 1
    This `response.setContentType("image/jpg");` looks fishy to me. You're setting that to the page's response object, aren't you? I'd expect that the contentType of the page would be e.g. `text/html`... Might not be the root of your problem, though. However, you do seem to be outputting data directly to the response AND expect that the jsp's html content is passed there, too... – Jan Chimiak Feb 18 '16 at 21:29
  • @JanChimiak Tried with text/html. Even the single image no longer appears and I get a blank white screen. – JasSy Feb 18 '16 at 21:47
  • 1
    That's not what i mean. At HTTP level you can have a single content type per request. Server sends a sequence of bytes + content type. Browser uses that to parse the bytes as text or as an image. In your output stream you first dump text then image, then text back again. See http://stackoverflow.com/questions/5243726/how-to-display-an-image-in-jsp Or base64 encode image or sth. – Jan Chimiak Feb 18 '16 at 21:49
  • 1
    I believe @JanChimiak is right about the content-type, and also you are putting in an `` tag where the `src=` attribute is supposed to refer to a _URL_ from where the image will be loaded, but you are putting the image byte data in there instead, which is not going to work. Aside: using `<%` and `%>` and putting Java code directly in the JSP has been considered bad practice for over a decade now. – Stephen P Feb 18 '16 at 21:50
  • @StephenP New to JSP and believe it or not, Googling lands me with tons of guides which involves Java code inside JSP. I am almost at the end and not do not want to restart all the coding to adhere to good practice. Future projects, sure. My issue involves loading data into image src in a loop for multiple images as you can see. Can pls help me with that or even a guide which can resolve this. Lost track of hours searching for answers and found nothing close. – JasSy Feb 18 '16 at 21:54
  • @jasSy I understand that old tutorials live forever, often pointing new coders in the wrong direction. For your issue I recommend the question Jan cited _[How to display an image in jsp?](http://stackoverflow.com/q/5243726/17300)_ and also the answer to _[How to retrieve and display images from a database in a JSP page?](http://stackoverflow.com/a/2341322/17300)_ – Stephen P Feb 18 '16 at 21:58
  • @StephenP I have seen the second link before. I don't understand . Am I supposed to create this path? foo.png looks hard coded. How am I going to loop in my case to dynamically create each jpg? I copied that servlet and its just sitting on my src file since a couple of hours back unsure on its use. I don't get how that servlet would know what image to load, each time I loop.. Lots of q's and possibly sounding silly but its whats ben buggin me for hours. – JasSy Feb 18 '16 at 22:04
  • Your webapp is installed somewhere —`${pageContext.request.contextPath}` is the installed path, `/images/` is a subdir of your webapp. Very important from the 1st link: `` is not a hard-coded path, but a path to a controller "getImage.action" (written, perhaps, as a Java servlet) which will fetch the specified `imageId` from the database and stream it out... but lacks the context path. ``. It's like getImage is a program that reads the image from the DB, instead of a file. – Stephen P Feb 19 '16 at 00:15

2 Answers2

1

src in img tag donot accept outputstream, you need to write outputstream else where and provide the link in img src eg:

<img class="k-profile-img" src="image.jsp" height="100px" border="1" style="float: left; overflow: hidden" width="33%">

and

image.jsp be like

<%
String dbURL = "jdbc:mysql://1.1.1.1:3306/db_name";
String dbUser = "";
String dbPass = "";
Connection conn;   
try{
    DriverManager.registerDriver(new com.mysql.jdbc.Driver());
    conn = DriverManager.getConnection(dbURL, dbUser, dbPass);

    Statement statement = conn.createStatement();
    ResultSet resultset =
            statement.executeQuery("select image from tablename");
    response.setContentType("image/jpg");
    while(resultset.next()) {
        Blob bl = resultset.getBlob(1);
        byte[] pict = bl.getBytes(1,(int)bl.length());
        }
        OutputStream o = response.getOutputStream(); 
        o.write(pict);
 }catch (Exception e){
     e.printStackTrace();
  }  
%>
Bimal Sharma
  • 134
  • 14
  • Works. Only issue is I am not able to upload different image on each iteration of the loop. I end up getting the same image (last image in database row). I tried to send the id value from the html page to the image.jsp via a session so I can call SELECT image from TABLENAME WHERE id = ? but same results. – JasSy Feb 19 '16 at 12:47
0

You can't just dump bytes into jsp page body and expect it to render in a browser. You have

<img class="k-profile-img" src="<%o.write(pict);%>"

This will print as roughly <img class"k-profile-img" src="˙Ř˙ŕ JFIF ˙áÚExif II* (a lot of binary data follows">

That's not something a browser can be expected to render correctly. It might show something, but just as well you may win the bingo or get hit by a meteorite.

You need to pass each type of content browsers can read in a separate HTTP response. Html as e.g. text/html and JPEG-compliant images as e.g. image/jpg. This means you can either:

  • Provide images from different pages (that's what the src HTML attribute points to - a href to a different location).
  • Provide images inline as yet another node of HTML content. This is usually done with base64-encoded content inside src, but be aware that not all older browsers support this (IE). See How to build base64 image src with jsp source?
Community
  • 1
  • 1
Jan Chimiak
  • 736
  • 7
  • 20