1

How can i do retrieval of image from database(mysql with blob data) and set it in table form(PrintWriter pw = response.getWriter(); pw.write("<img src=""/>"); ) at servlet and display it at JSP page, making a table dynamically(base on my database data)(Although i'm not sure whether can it be achievable) But if it is achievable, how can i do that? If it is not achievable. What is the suggested possible answer? Your help will be much appreciated. Here is my code :

     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
             byte[] binaryStream;
        ArrayList<RetrievingPost> combine=new ArrayList<RetrievingPost>();

           try{
                             // Register JDBC driver
                             Class.forName("com.mysql.jdbc.Driver");

                             // Open a connection
                             Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/asq?characterEncoding=UTF-8&useSSL=false", "root", "root");

                             // Execute SQL query
                             Statement pst = connection.createStatement();
                             String sql;
                             sql = "select profilepic, displayname, r.userId, friendId from registration r inner join friendlist fl on r.userId=fl.userId where r.emailAddress='" + emailAddress + "'";
                             ResultSet rs = pst.executeQuery(sql);

                             // Extract data from result set
                             while(rs.next()){
                                //Retrieve by column name
                         Retrieving retrieve=new Retrieve();
                                userId  = rs.getInt("userId");
                                 System.out.println(userId+"---------userId-------");
                                friendId =rs.getInt("friendId");
                                displayname=rs.getString("displayname");

                              binaryStream = rs.getBytes("profilepic");
    retrieve.setFriendId(friendId);
    retrieve.setDisplayName(displayname);
     retrieve.setBinaryStream(binaryStream);
     Combine.add(retrieve);
                        }


                             // Clean-up environment
                             rs.close();
                             pst.close();
                             connection.close();
                          }catch(SQLException se){
                             //Handle errors for JDBC
                             se.printStackTrace();
                          }catch(Exception e){
                             //Handle errors for Class.forName
                             e.printStackTrace();
                          }finally{
                             //finally block used to close resources
                             try{
                                if(stmt!=null)
                                   stmt.close();
                             }catch(SQLException se2){
                             }// nothing we can do
                             try{
                                if(conn!=null)
                                conn.close();
                             }catch(SQLException se){
                                se.printStackTrace();
                             }//end finally try
                          } //end try

        for(int j=0;j<combine.size();j++){
          PrintWriter pw = response.getWriter();
                                       pw.write("<HTML><BODY>");
                                       pw.write("<TABLE border='1'>");
                                       pw.write("<TR>");
                                       pw.write("<TD>");



                                       pw.write(combine.get(i).getDisplayname());
                                       pw.write("</TD>");
                                    //if possible, i would like to display my image into the table
                                       pw.write("<TD>");
                                       String tPosted=combine.get(i).getTimePosted().toString();
                                       pw.write(tPosted);
                                       pw.write("</TD>");
                                       pw.write("</TR>");
                                     }}
getServletContext().getRequestDispatcher("/DisplayingImage.jsp").include(request, response);}

This is my bean

package registration;

import java.io.InputStream;
import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.http.Part;

public class RetrievingPost {
int userId;
int friendId;
String privacyDesc;
String status;
String description;
Timestamp timePosted;
String category;
String displayname;

byte[] binaryStream ;
public byte[] getBinaryStream() {
    return binaryStream;
}
public void setBinaryStream(byte[]  binaryStream) {
    this.binaryStream = binaryStream;
}

public String getDisplayname() {
    return displayname;
}
public void setDisplayname(String displayname) {
    this.displayname = displayname;
}
public String getCategory() {
    return category;
}
public void setCategory(String category) {
    this.category = category;
}
public RetrievingPost(int userId,Timestamp timePosted, String privacyDesc, String status, String post, int friendId){
    this.userId=userId;
    this.timePosted=timePosted;
    this.privacyDesc=privacyDesc;
    this.status=status;
    this.description=description;
    this.friendId=friendId;

}
public RetrievingPost(){
    super();
}



public int getUserId() {
    return userId;
}
public void setUserId(int userId) {
    this.userId = userId;
}
public int getFriendId() {
    return friendId;
}
public void setFriendId(int friendId) {
    this.friendId = friendId;
}
public String getPrivacyDesc() {
    return privacyDesc;
}
public void setPrivacyDesc(String privacyDesc) {
    this.privacyDesc = privacyDesc;
}
public String getStatus() {
    return status;
}
public void setStatus(String status) {
    this.status = status;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
public Timestamp getTimePosted() {
    return timePosted;
}
public void setTimePosted(Timestamp timePosted) {
    this.timePosted = timePosted;
}
}
Qccccc
  • 23
  • 1
  • 7
  • 1
    Just for the record: it's not good practice to keep images for your app in the db as blob. Instead it's better to store string representations of their urls, and store images in the filesystem. The reasons are: 1. Storing blobs makes db bigger and slower, and fetching blobs is slow. 2. This is not that flexible, if you want to update the image, it's much easier in all senses to write it directly to the filesystem instead of db. Not the answer, but maybe it matters. – Battle_Slug Jul 13 '16 at 15:35

1 Answers1

0

See the answer to this question. Focus on the servlet explanation, as you will use it for your page.

Basically, the process to follow will be:

  1. Create a servlet whose only purpose will only be to dispatch images, and make sure to receive the id of the user via GET parameter (for example, create a servlet called ImageServlet with the parameter userId.

    @WebServlet("/ImageServlet")
    public class ImageServlet extends HttpServlet {
    //...
       public void doGet( HttpServletRequest request, HttpServletResponse response){
          Integer userId = Integer.parseInt( request.getParameter( "userId" ) );
    
  2. Within that servlet, connect to your DB.

    public void doGet( /*...*/ ){
       Integer userId = //...
       //super method to extract the data from your DB
       RetrievingPost userInfo = new UserDAO( ).fetchById( userId );
    
  3. super important Mark the response's mime type to be "image/jpg" (or png, jpeg, etc).

    response.setContentType( "image/jpg" );
    
  4. Extract the image and write it to the outputStream object. Use some I/O buffer to help you

    BufferedOutputStream bos = new BufferedOutputStream( response.getOutputStream( ) );
    bos.write( userInfo.getBinaryStream( ) );
    bos.flush( );
    bos.close( );
    

    EDIT

  5. In the JSP page (or HTML) put an image tag referencing to the servlet.

    <!--Set the param "userId" to a custom one with JS or JSP-->
    <img src="/my_project/ImageServlet?userId=50"/>
    
Community
  • 1
  • 1
McSonk
  • 493
  • 1
  • 4
  • 11
  • Sorry, just to check with you, what if there are more than 1 type of image as mention in no3. My database has .jpeg, .png, .jpg, .gif. Therefore, i am unable to define specifically whether it will display jpg and etc. Is there any solution to that? In other words, is there a more dynamic way to solve this? – Qccccc Jul 13 '16 at 14:48
  • In the strict sense, **there is not such a thing as a "generic" mime type for images**. However, please note that, not matter if your image is an JPG, PNG, GIF, etc, the browser will correctly show an image with a mime type like "image/png" or "image/jpg". If you want to be strict, put an extra field in your database to identify the image type and send the correct MIME, but usually you don't have to do it. For mor information, please visit [http://superuser.com/questions/979135/is-there-a-generic-mime-type-for-all-image-files] – McSonk Jul 13 '16 at 15:10