Inserting and Retrieving Images From Database Using Servlets and JSP

This article is just an extension to my previous article that stores images or data using swing components. In this article we are using the same thing but the way of doing is different. We will be using Servlets and JSP to store and retrieve images from a database. If you haven’t gone through my previous article then kindly have a look at it.

Inserting Image in Database using Java

We’ll be using the same database that has been used in the previous article.

Our screen shot will be like the following.

Form

The following is the source code for it.

Index.jsp

<%--

     Document   : index

    Created on : Nov 14, 2013, 11:36:25 AM

    Author     : Vishal.Gilbile

--%>

 

<%@ 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>

    <form name="f1" method="post" enctype="multipart/form-data" action="addEmployee">

    <h2>

        Add Image In DB

    </h2>

    <table>

        <tr>

            <td>

                <table>

                    <tr>

                        <td>Name:</td>

                        <td><input type="text" name="txtName" value="" /></td>

                    </tr>

                    <tr>

                        <td>Address:</td>

                        <td><input type="text" name="txtAddress" value="" /></td>

                    </tr>

                    <tr>

                        <td>Salary:</td>

                        <td><input type="text" name="txtSalary" value="" /></td>

                    </tr>

                    <tr>

                        <td>Photo:</td>

                        <td><input type="file" name="flPhoto" value="" /></td>

                    </tr>

                    <tr>

                        <td colspan="2" align="right"><input type="submit" value="Save" name="btnSave" /></td>

                    </tr>

                </table>

            </td>

            <td>

                <table>

                    <tr>

                        <td style="width: 450px; height: auto;">

                            <iframe name="ifs" src="DisplayData" style="width: 550px; height: 300px"></iframe>

                        </td>

                    </tr>

                </table>

            </td>

        </tr>

    </table>

    </form>

</body>

</html>

AddEmployee.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.Iterator;
import java.util.List;
import javax.servlet.annotation.MultipartConfig;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 
/**
 * @author Vishal.Gilbile
 */
@MultipartConfig(location = "/tmp", fileSizeThreshold = 1024 * 1024,
        maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 5 * 5)
public class addEmployee extends HttpServlet {
 
    String name, add;
    float salary;
    FileItem flItem = null;
 
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Connection con = null;
        CallableStatement stat = null;
        try {
            long maxFileSize = (2 * 1024 * 1024);
            int maxMemSize = (2 * 1024 * 1024);
//         final String path = "/tmp";
            boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
            if (isMultiPart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = upload.parseRequest(request);
                Iterator<FileItem> iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem fileItem = iter.next();
                    if (fileItem.isFormField()) {
                        processFormField(fileItem);
                    } else {
                        flItem = fileItem;
                    }
                }
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                con = DriverManager.getConnection("jdbc:odbc:myCon", "", "");
                stat = con.prepareCall("{call prc_AddEmployee(?,?,?,?)}");
                stat.setString(1, name);
                stat.setString(2, add);
                stat.setFloat(3, salary);
                stat.setBinaryStream(4, flItem.getInputStream(), (int) flItem.getSize());
                // stat.setBinaryStream(4, (InputStream) itemPhoto.getInputStream(), (int) itemPhoto.getSize());
                int rows = stat.executeUpdate();
                if (rows > 0) {
                    response.sendRedirect("index.jsp");
                } else {
                    out.println("<html>");
                    out.println("<head>");
                    out.println("<title>Error Adding Employee</title>");
                    out.println("</head>");
                    out.println("<body>");
                    out.println("<h2>Error Adding Employee Data</h2>");
                    out.println("</body>");
                    out.println("</html>");
                }
            }
        } catch (Exception ex) {
            out.println(ex.getMessage());
        } finally {
            try {
                con.close();
                stat.close();
                out.close();
            } catch (Exception ex) {
                out.println(ex.getMessage());
            }
        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    private void processFormField(FileItem item) {
        //String na = item.getFieldName();
        if (item.getFieldName().equals("txtName")) {
            name = item.getString();
        } else if (item.getFieldName().equals("txtAddress")) {
            add = item.getString();
        } else if (item.getFieldName().equals("txtSalary")) {
            String sal = item.getString();
            salary = Float.parseFloat(sal);
        }
    }
 
    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
 
DisplayData.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
 
/**
 * @author Vishal.Gilbile
 */
public class DisplayData extends HttpServlet {
 
    Connection con;
    CallableStatement stat;
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.   
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            con = DriverManager.getConnection("jdbc:odbc:myCon", "", "");
            stat = con.prepareCall("{call prc_getEmployees}");
            ResultSet rs = stat.executeQuery();
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet DisplayData</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<table style='width:100%; height:auto;'>");
            out.println("<thead><td>ID</td><td>Name</td><td>Address</td><td>Salary</td><td align='center'>Photo</td></thead>");
            while (rs.next()) {
                int id = rs.getInt(1);
                out.println("<td>" + id + "</td>");
                out.println("<td>" + rs.getString(2) + "</td>");
                out.println("<td>" + rs.getString(3) + "</td>");
                out.println("<td>" + rs.getString(4) + "</td>");
                out.println("<td style='width:150px; height:125px;'><img src='" + "retriveImage?" + id + "' style='width:150px; height:125px;'/></td></tr>");
            }
            out.println("</table>");
            out.println("</body>");
            out.println("</html>");
        } catch (ClassNotFoundException ex) {
            out.println(ex.getMessage());
        } catch (SQLException ex) {
            out.println(ex.getMessage());
        } finally {
            try {
                con.close();
                out.close();
            } catch (SQLException ex) {
                out.println(ex.getMessage());
            }
        }
    }
 
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.   
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    /**
     * Handles the HTTP <code>POST</code> method.   
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    /**
     * Returns a short description of the servlet.    
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
 
RetrieveImage.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
 
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import javax.servlet.ServletOutputStream;
 
/** 
 * @author Vishal.Gilbile
 */
public class retriveImage extends HttpServlet {
 
    Connection con;
    CallableStatement stat;
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.    
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //response.setContentType("text/html;charset=UTF-8");
        response.setContentType("image/jpeg");
        //PrintWriter out = response.getWriter();
        Blob ePhoto = null;
        byte[] rawBytes = null;
        ServletOutputStream out = response.getOutputStream();
        try {
            /*
             * TODO output your page here. You may use following sample code.
             */
            //byte[] rawBytes = null;
            String id = request.getQueryString();
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            con = DriverManager.getConnection("jdbc:odbc:myCon", "", "");
            stat = con.prepareCall("{call prc_getEPhoto(?)}");
            stat.setInt(1, Integer.parseInt(id));
            ResultSet rs = stat.executeQuery();
            rs.next();
//            out.println("<html>");
//            out.println("<head>");
//            out.println("<title>Servlet retriveImage</title>");
//            out.println("</head>");
//            out.println("<body>");
            rawBytes = rs.getBytes(1);
            out.write(rawBytes);
//            out.println("</body>");
//            out.println("</html>");
            out.flush();
            stat.close();
        } catch (Exception ex) {
            out.println(ex.getMessage());
        } finally {
            try {
                con.close();
                out.close();
            } catch (Exception ex) {
            }
        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

The following is the output for it.
 
Insert Image

Save Image 

Up Next
    Ebook Download
    View all
    Learn
    View all