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.
 
 
We’ll be using the same database that has been used in the previous article.
 
Our screenshot will be like the following.
 
Form 
 
The following is the source code for it.
 
Index.jsp
  1. <%@ Page ContentType="text/html" pageEncoding="UTF-8" %>  
  2. <!DOCTYPE html>  
  3. <html>  
  4. <head>  
  5.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  6.     <title>JSP Page</title>  
  7. </head>  
  8. <body>  
  9.     <form name="f1" method="post" enctype="multipart/form-data" action="addEmployee">  
  10.     <h2>  
  11.         Add Image In DB  
  12.     </h2>  
  13.     <table>  
  14.         <tr>  
  15.             <td>  
  16.                 <table>  
  17.                     <tr>  
  18.                         <td>Name:</td>  
  19.                         <td><input type="text" name="txtName" value="" /></td>  
  20.                     </tr>  
  21.                     <tr>  
  22.                         <td>Address:</td>  
  23.                         <td><input type="text" name="txtAddress" value="" /></td>  
  24.                     </tr>  
  25.                     <tr>  
  26.                         <td>Salary:</td>  
  27.                         <td><input type="text" name="txtSalary" value="" /></td>  
  28.                     </tr>  
  29.                     <tr>  
  30.                         <td>Photo:</td>  
  31.                         <td><input type="file" name="flPhoto" value="" /></td>  
  32.                     </tr>  
  33.                     <tr>  
  34.                         <td colspan="2" align="right"><input type="submit" value="Save" name="btnSave" /></td>  
  35.                     </tr>  
  36.                 </table>  
  37.             </td>  
  38.             <td>  
  39.                 <table>  
  40.                     <tr>  
  41.                         <td style="width: 450px; height: auto;">  
  42.                             <iframe name="ifs" src="DisplayData" style="width: 550px; height: 300px"></iframe>  
  43.                         </td>  
  44.                     </tr>  
  45.                 </table>  
  46.             </td>  
  47.         </tr>  
  48.     </table>  
  49.     </form>  
  50. </body>  
  51. </html>  

AddEmployee.java

  1. /* 
  2.  * To change this template, choose Tools | Templates 
  3.  * and open the template in the editor. 
  4.  */  
  5. import java.io.IOException;  
  6. import java.io.PrintWriter;  
  7. import javax.servlet.ServletException;  
  8. import javax.servlet.http.HttpServlet;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11. import java.sql.*;  
  12. import java.util.Iterator;  
  13. import java.util.List;  
  14. import javax.servlet.annotation.MultipartConfig;  
  15. import org.apache.commons.fileupload.FileItem;  
  16. import org.apache.commons.fileupload.FileItemFactory;  
  17. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  18. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  19.    
  20. /** 
  21.  * @author Vishal.Gilbile 
  22.  */  
  23. @MultipartConfig(location = "/tmp", fileSizeThreshold = 1024 * 1024,  
  24.         maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 5 * 5)  
  25. public class addEmployee extends HttpServlet {  
  26.    
  27.     String name, add;  
  28.     float salary;  
  29.     FileItem flItem = null;  
  30.    
  31.     /** 
  32.      * Processes requests for both HTTP <code>GET</code> and <code>POST</code> 
  33.      * methods. 
  34.      * @param request servlet request 
  35.      * @param response servlet response 
  36.      * @throws ServletException if a servlet-specific error occurs 
  37.      * @throws IOException if an I/O error occurs 
  38.      */  
  39.     protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
  40.             throws ServletException, IOException {  
  41.         response.setContentType("text/html;charset=UTF-8");  
  42.         PrintWriter out = response.getWriter();  
  43.         Connection con = null;  
  44.         CallableStatement stat = null;  
  45.         try {  
  46.             long maxFileSize = (2 * 1024 * 1024);  
  47.             int maxMemSize = (2 * 1024 * 1024);  
  48. //         final String path = "/tmp";  
  49.             boolean isMultiPart = ServletFileUpload.isMultipartContent(request);  
  50.             if (isMultiPart) {  
  51.                 FileItemFactory factory = new DiskFileItemFactory();  
  52.                 ServletFileUpload upload = new ServletFileUpload(factory);  
  53.                 List items = upload.parseRequest(request);  
  54.                 Iterator<FileItem> iter = items.iterator();  
  55.                 while (iter.hasNext()) {  
  56.                     FileItem fileItem = iter.next();  
  57.                     if (fileItem.isFormField()) {  
  58.                         processFormField(fileItem);  
  59.                     } else {  
  60.                         flItem = fileItem;  
  61.                     }  
  62.                 }  
  63.                 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
  64.                 con = DriverManager.getConnection("jdbc:odbc:myCon""""");  
  65.                 stat = con.prepareCall("{call prc_AddEmployee(?,?,?,?)}");  
  66.                 stat.setString(1, name);  
  67.                 stat.setString(2, add);  
  68.                 stat.setFloat(3, salary);  
  69.                 stat.setBinaryStream(4, flItem.getInputStream(), (int) flItem.getSize());  
  70.                 // stat.setBinaryStream(4, (InputStream) itemPhoto.getInputStream(), (int) itemPhoto.getSize());  
  71.                 int rows = stat.executeUpdate();  
  72.                 if (rows > 0) {  
  73.                     response.sendRedirect("index.jsp");  
  74.                 } else {  
  75.                     out.println("<html>");  
  76.                     out.println("<head>");  
  77.                     out.println("<title>Error Adding Employee</title>");  
  78.                     out.println("</head>");  
  79.                     out.println("<body>");  
  80.                     out.println("<h2>Error Adding Employee Data</h2>");  
  81.                     out.println("</body>");  
  82.                     out.println("</html>");  
  83.                 }  
  84.             }  
  85.         } catch (Exception ex) {  
  86.             out.println(ex.getMessage());  
  87.         } finally {  
  88.             try {  
  89.                 con.close();  
  90.                 stat.close();  
  91.                 out.close();  
  92.             } catch (Exception ex) {  
  93.                 out.println(ex.getMessage());  
  94.             }  
  95.         }  
  96.     }   
  97.     // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">  
  98.     /** 
  99.      * Handles the HTTP <code>GET</code> method. 
  100.      * 
  101.      * @param request servlet request 
  102.      * @param response servlet response 
  103.      * @throws ServletException if a servlet-specific error occurs 
  104.      * @throws IOException if an I/O error occurs 
  105.      */  
  106.     @Override  
  107.     protected void doGet(HttpServletRequest request, HttpServletResponse response)  
  108.             throws ServletException, IOException {  
  109.         processRequest(request, response);  
  110.     }   
  111.     private void processFormField(FileItem item) {  
  112.         //String na = item.getFieldName();  
  113.         if (item.getFieldName().equals("txtName")) {  
  114.             name = item.getString();  
  115.         } else if (item.getFieldName().equals("txtAddress")) {  
  116.             add = item.getString();  
  117.         } else if (item.getFieldName().equals("txtSalary")) {  
  118.             String sal = item.getString();  
  119.             salary = Float.parseFloat(sal);  
  120.         }  
  121.     }  
  122.    
  123.     /** 
  124.      * Handles the HTTP <code>POST</code> method. 
  125.      * 
  126.      * @param request servlet request 
  127.      * @param response servlet response 
  128.      * @throws ServletException if a servlet-specific error occurs 
  129.      * @throws IOException if an I/O error occurs 
  130.      */  
  131.     @Override  
  132.     protected void doPost(HttpServletRequest request, HttpServletResponse response)  
  133.             throws ServletException, IOException {  
  134.         processRequest(request, response);  
  135.     }   
  136.     /** 
  137.      * Returns a short description of the servlet. 
  138.      * 
  139.      * @return a String containing servlet description 
  140.      */  
  141.     @Override  
  142.     public String getServletInfo() {  
  143.         return "Short description";  
  144.     }// </editor-fold>  
  145. }

 

  1. /* 
  2.  * To change this template, choose Tools | Templates 
  3.  * and open the template in the editor. 
  4.  */  
  5.    
  6. DisplayData.java  
  7.   
  8. import java.io.IOException;  
  9. import java.io.PrintWriter;  
  10. import javax.servlet.ServletException;  
  11. import javax.servlet.http.HttpServlet;  
  12. import javax.servlet.http.HttpServletRequest;  
  13. import javax.servlet.http.HttpServletResponse;  
  14. import java.sql.*;  
  15.    
  16. /** 
  17.  * @author Vishal.Gilbile 
  18.  */  
  19. public class DisplayData extends HttpServlet {  
  20.    
  21.     Connection con;  
  22.     CallableStatement stat;   
  23.     /** 
  24.      * Processes requests for both HTTP <code>GET</code> and <code>POST</code> 
  25.      * methods.    
  26.      * @param request servlet request 
  27.      * @param response servlet response 
  28.      * @throws ServletException if a servlet-specific error occurs 
  29.      * @throws IOException if an I/O error occurs 
  30.      */  
  31.     protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
  32.             throws ServletException, IOException {  
  33.         response.setContentType("text/html;charset=UTF-8");  
  34.         PrintWriter out = response.getWriter();  
  35.         try {  
  36.             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
  37.             con = DriverManager.getConnection("jdbc:odbc:myCon""""");  
  38.             stat = con.prepareCall("{call prc_getEmployees}");  
  39.             ResultSet rs = stat.executeQuery();  
  40.             out.println("<html>");  
  41.             out.println("<head>");  
  42.             out.println("<title>Servlet DisplayData</title>");  
  43.             out.println("</head>");  
  44.             out.println("<body>");  
  45.             out.println("<table style='width:100%; height:auto;'>");  
  46.             out.println("<thead><td>ID</td><td>Name</td><td>Address</td><td>Salary</td><td align='center'>Photo</td></thead>");  
  47.             while (rs.next()) {  
  48.                 int id = rs.getInt(1);  
  49.                 out.println("<td>" + id + "</td>");  
  50.                 out.println("<td>" + rs.getString(2) + "</td>");  
  51.                 out.println("<td>" + rs.getString(3) + "</td>");  
  52.                 out.println("<td>" + rs.getString(4) + "</td>");  
  53.                 out.println("<td style='width:150px; height:125px;'><img src='" + "retriveImage?" + id + "' style='width:150px; height:125px;'/></td></tr>");  
  54.             }  
  55.             out.println("</table>");  
  56.             out.println("</body>");  
  57.             out.println("</html>");  
  58.         } catch (ClassNotFoundException ex) {  
  59.             out.println(ex.getMessage());  
  60.         } catch (SQLException ex) {  
  61.             out.println(ex.getMessage());  
  62.         } finally {  
  63.             try {  
  64.                 con.close();  
  65.                 out.close();  
  66.             } catch (SQLException ex) {  
  67.                 out.println(ex.getMessage());  
  68.             }  
  69.         }  
  70.     }  
  71.    
  72.     // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">  
  73.     /** 
  74.      * Handles the HTTP <code>GET</code> method.    
  75.      * @param request servlet request 
  76.      * @param response servlet response 
  77.      * @throws ServletException if a servlet-specific error occurs 
  78.      * @throws IOException if an I/O error occurs 
  79.      */  
  80.     @Override  
  81.     protected void doGet(HttpServletRequest request, HttpServletResponse response)  
  82.             throws ServletException, IOException {  
  83.         processRequest(request, response);  
  84.     }   
  85.     /** 
  86.      * Handles the HTTP <code>POST</code> method.    
  87.      * @param request servlet request 
  88.      * @param response servlet response 
  89.      * @throws ServletException if a servlet-specific error occurs 
  90.      * @throws IOException if an I/O error occurs 
  91.      */  
  92.     @Override  
  93.     protected void doPost(HttpServletRequest request, HttpServletResponse response)  
  94.             throws ServletException, IOException {  
  95.         processRequest(request, response);  
  96.     }   
  97.     /** 
  98.      * Returns a short description of the servlet.      
  99.      * @return a String containing servlet description 
  100.      */  
  101.     @Override  
  102.     public String getServletInfo() {  
  103.         return "Short description";  
  104.     }// </editor-fold>  
  105. }  

RetrieveImage.java

  1. /* 
  2.  * To change this template, choose Tools | Templates 
  3.  * and open the template in the editor. 
  4.  */  
  5.    
  6. import java.io.IOException;  
  7. import javax.servlet.ServletException;  
  8. import javax.servlet.http.HttpServlet;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11. import java.sql.*;  
  12. import javax.servlet.ServletOutputStream;  
  13.    
  14. /**   
  15.  * @author Vishal.Gilbile 
  16.  */  
  17. public class retriveImage extends HttpServlet {  
  18.    
  19.     Connection con;  
  20.     CallableStatement stat;   
  21.     /** 
  22.      * Processes requests for both HTTP 
  23.      * <code>GET</code> and 
  24.      * <code>POST</code> methods.      
  25.      * @param request servlet request 
  26.      * @param response servlet response 
  27.      * @throws ServletException if a servlet-specific error occurs 
  28.      * @throws IOException if an I/O error occurs 
  29.      */  
  30.     protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
  31.             throws ServletException, IOException {  
  32.         //response.setContentType("text/html;charset=UTF-8");  
  33.         response.setContentType("image/jpeg");  
  34.         //PrintWriter out = response.getWriter();  
  35.         Blob ePhoto = null;  
  36.         byte[] rawBytes = null;  
  37.         ServletOutputStream out = response.getOutputStream();  
  38.         try {  
  39.             /* 
  40.              * TODO output your page here. You may use following sample code. 
  41.              */  
  42.             //byte[] rawBytes = null;  
  43.             String id = request.getQueryString();  
  44.             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
  45.             con = DriverManager.getConnection("jdbc:odbc:myCon""""");  
  46.             stat = con.prepareCall("{call prc_getEPhoto(?)}");  
  47.             stat.setInt(1, Integer.parseInt(id));  
  48.             ResultSet rs = stat.executeQuery();  
  49.             rs.next();  
  50. //            out.println("<html>");  
  51. //            out.println("<head>");  
  52. //            out.println("<title>Servlet retriveImage</title>");  
  53. //            out.println("</head>");  
  54. //            out.println("<body>");  
  55.             rawBytes = rs.getBytes(1);  
  56.             out.write(rawBytes);  
  57. //            out.println("</body>");  
  58. //            out.println("</html>");  
  59.             out.flush();  
  60.             stat.close();  
  61.         } catch (Exception ex) {  
  62.             out.println(ex.getMessage());  
  63.         } finally {  
  64.             try {  
  65.                 con.close();  
  66.                 out.close();  
  67.             } catch (Exception ex) {  
  68.             }  
  69.         }  
  70.     }   
  71.     // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">  
  72.     /** 
  73.      * Handles the HTTP 
  74.      * <code>GET</code> method. 
  75.      * 
  76.      * @param request servlet request 
  77.      * @param response servlet response 
  78.      * @throws ServletException if a servlet-specific error occurs 
  79.      * @throws IOException if an I/O error occurs 
  80.      */  
  81.     @Override  
  82.     protected void doGet(HttpServletRequest request, HttpServletResponse response)  
  83.             throws ServletException, IOException {  
  84.         processRequest(request, response);  
  85.     }   
  86.     /** 
  87.      * Handles the HTTP 
  88.      * <code>POST</code> method. 
  89.      * 
  90.      * @param request servlet request 
  91.      * @param response servlet response 
  92.      * @throws ServletException if a servlet-specific error occurs 
  93.      * @throws IOException if an I/O error occurs 
  94.      */  
  95.     @Override  
  96.     protected void doPost(HttpServletRequest request, HttpServletResponse response)  
  97.             throws ServletException, IOException {  
  98.         processRequest(request, response);  
  99.     }   
  100.     /** 
  101.      * Returns a short description of the servlet. 
  102.      * 
  103.      * @return a String containing servlet description 
  104.      */  
  105.     @Override  
  106.     public String getServletInfo() {  
  107.         return "Short description";  
  108.     }// </editor-fold>  
  109. }   
The following is the output for it.
 
Insert Image 
 
Save Image