SHINERAJ ARATHIL
SHINERAJ ARATHIL

Reputation: 476

Unable to show images in JSP from database using servlet

I am trying to fetch and display , images saved as blob on the JSP from mysql database using servlet. I wrote this code referring many websites and still , its not working. I am not getting any type of errors. its showing like this

enter image description here

I have created table using

create table contacts(id int not null auto_increment,
name varchar(40),
second varchar(40),
photo blob,
primary key(id));

This my Servlet DisplayServlet.java

@WebServlet("/DisplayServlet")
public class DisplayServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    public void init() throws ServletException {

    }

public DisplayServlet() {
    super();
}


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String imageId = request.getParameter("id");
    System.out.println(imageId);
    InputStream sImage;



    // Check if ID is supplied to the request.
    if (imageId == null) {
        // Do your thing if the ID is not supplied to the request.
        // Throw an exception, or send 404, or show default/warning image, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    try{
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/projectbuy", "root","root");
        stmt = conn.prepareStatement("select photo from contacts where id=" + imageId);
        rs = stmt.executeQuery();
        if(rs.next()){
            System.out.println("Inside RS");
            byte[] bytearray = new byte[1048576];
            int size=0;
            sImage = rs.getBinaryStream(4);
            response.reset();
            response.setContentType("image/jpeg");
            while((size = sImage.read(bytearray)) != -1 ){
                response.getOutputStream().
                write(bytearray,0,size);
            }
        }

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

}

Here is my jsp page , imagedemo.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>

        <h1>Hello World!</h1>


        <img src="DisplayServlet?id=1" height="150px" width="150px" alt="ProfilePic">

    </body>
</html>

Finally this is my xml file

<servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

<servlet>
    <servlet-name>DisplayServlet</servlet-name>
    <servlet-class>DisplayServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>DisplayServlet</servlet-name>
    <url-pattern>/DisplayServlet/*</url-pattern>
</servlet-mapping>

Upvotes: 1

Views: 801

Answers (1)

Alex Chernyshev
Alex Chernyshev

Reputation: 1745

You're selecting only one column:

stmt = conn.prepareStatement("select photo from contacts where id=" + imageId);

but later trying to retrieve 4th:

sImage = rs.getBinaryStream(4);

And you have no flush() call afer writing loop. Also it's a good idea to use connection from pool instead of instantiating it directly from driverManager, and to close it after work.

Upvotes: 1

Related Questions