How to upload, store and retrieve images into MySQL database using JSP and Servlet. In this JSP and servlet example, let’s create a Java web project to upload the image and view image using MYSQL.
There are two options on the home page of the application, “Add Image” and “View Image”, When the user clicks on Add image, an image uploading page will open, where the user can browse and upload the image that will stored in MySQL database.
Another option is to view the image, which is when the user clicks on view image. All the uploaded images will be displayed in the list view that is available in the database table.
Store and Read Image in MYSQL using JSP and Servlet
- Create Database “imagedb” and table with the name “imagedata”.
- Create a simple Java web maven project.
- Add designing pages.
- Implement servlets to handle requests and responses.
- Create models to handle database connections.
Create a database with the name “imagedb” and a table with the name “imagedata” with the column name id, name, and uploadImage.
Maven Dependencies
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.21</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.5</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>
ImageBean.java
package com.imageModel.java; import java.sql.Blob; public class ImageBean { private long id; private String name; private Blob UploadImage; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Blob getUploadImage() { return UploadImage; } public void setUploadImage(Blob uploadImage) { UploadImage = uploadImage; } }
Image Models
package com.imageModel.java; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class ImageModel { protected static Connection initializeDatabase() throws SQLException, ClassNotFoundException { String dbDriver = "com.mysql.cj.jdbc.Driver"; String dbURL = "jdbc:mysql://localhost:3306/"; String dbName = "imagedb"; String dbUsername = "root"; String dbPassword = "root"; Class.forName(dbDriver); Connection con = DriverManager.getConnection(dbURL + dbName, dbUsername, dbPassword); return con; } public Integer nextPk() throws Exception { Connection conn = null; int pk = 0; try { conn = ImageModel.initializeDatabase(); PreparedStatement ps = conn.prepareStatement("SELECT MAX(ID) FROM imagedata"); ResultSet rs = ps.executeQuery(); while (rs.next()) { pk = rs.getInt(1); } rs.close(); } catch (Exception e) { } return pk + 1; } public long add(ImageBean bean){ Connection conn = null; ImageModel model = new ImageModel(); int pk = 0; try { conn = ImageModel.initializeDatabase(); pk = nextPk(); System.out.println(pk); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("INSERT INTO IMAGEDATA VALUES(?,?,?)"); System.out.println(bean.getName()); System.out.println(bean.getUploadImage()); ps.setLong(1, pk); ps.setString(2, bean.getName()); ps.setBlob(3, bean.getUploadImage()); ps.executeUpdate(); System.out.println("ecute"); conn.commit(); ps.close(); } catch (Exception e) { e.printStackTrace(); try { conn.rollback(); } catch (Exception e2) { e.printStackTrace(); System.out.println(e.getStackTrace()); } } return pk; } public List list() throws Exception { ArrayList list = new ArrayList (); Connection conn = null; System.out.println("list called"); conn = ImageModel.initializeDatabase(); PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM IMAGEDATA "); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { ImageBean bean = new ImageBean(); bean.setId(rs.getLong(1)); bean.setName(rs.getString(2)); bean.setUploadImage(rs.getBlob(3)); list.add(bean); } return list; } }
Image Controllers
AddImageCtl.java
package com.imageModel.java; import java.beans.beancontext.BeanContext; import java.io.IOException; import java.io.InputStream; import java.sql.Blob; import java.sql.SQLException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import javax.sql.rowset.serial.SerialBlob; import javax.sql.rowset.serial.SerialException; /** * Servlet implementation class AddImageCtl */ @WebServlet(name = "AddImageCtl", urlPatterns = { "/AddImageCtl" }) @MultipartConfig(maxFileSize = 16177215) public class AddImageCtl extends HttpServlet { private static final long serialVersionUID = 1L; public static final String OP_SEARCH = "Search"; public static final String OP_SAVE = "Save"; public static final String OP_UPDATE = "Update"; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher requestDispatcher = request.getRequestDispatcher("addimage.jsp"); requestDispatcher.forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ImageBean bean = new ImageBean(); ImageModel model = new ImageModel(); String name = request.getParameter("name"); String op = request.getParameter("opeartion"); Blob blob = null; Part filepart; try { filepart = request.getPart("uplodeimage"); InputStream inputStream = null; inputStream = filepart.getInputStream(); byte[] b = new byte[inputStream.available()]; System.out.println(b); inputStream.read(b); try { blob = new SerialBlob(b); } catch (SerialException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } System.out.println(blob); bean.setUploadImage(blob); bean.setName(name); long pk = model.add(bean); } catch (Exception e) { e.printStackTrace(); } RequestDispatcher requestDispatcher = request.getRequestDispatcher("addimage.jsp"); requestDispatcher.forward(request, response); } }
imageCtl.java
package com.imageModel.java; import java.io.IOException; import java.io.OutputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class imageCtl */@WebServlet(name="imageCtl", urlPatterns = {"/imageCtl"}) public class imageCtl extends HttpServlet{ private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/jpg"); int id = Integer.parseInt(request.getParameter("oid")); Connection conn; try { conn = ImageModel.initializeDatabase(); String sql = "SELECT * FROM IMAGEDATA WHERE ID ='"+id+"'"; PreparedStatement ps; ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); if(rs.next()){ byte [] imageData = rs.getBytes("UploadImage"); // extract byte data from the resultset.. OutputStream os = response.getOutputStream(); // output with the help of outputStream os.write(imageData); os.flush(); os.close(); } }catch (Exception e1) { e1.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
ImageListCtl.java
package com.imageModel.java; import java.io.IOException; import java.io.InputStream; import java.sql.Blob; import java.sql.SQLException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import javax.sql.rowset.serial.SerialBlob; import javax.sql.rowset.serial.SerialException; /** * Servlet implementation class NewsDeatilCtl */@WebServlet(name="ImageListCtl", urlPatterns = {"/ImageListCtl"}) public class ImageListCtl extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ImageModel model = new ImageModel(); ImageBean bean = null; List list = null; try { list = model.list(); System.out.println("in do get"); request.setAttribute("list",list); RequestDispatcher rd = request.getRequestDispatcher("imageview.jsp"); rd.forward(request, response); System.out.println("list called"); } catch (Exception e) { e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
Header.jsp
<%@page import="com.imageModel.java.ImageBean"%> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </head> <body> <nav class="navbar navbar-expand-lg navbar navbar-secondary bg-secondary"> <a class="navbar-brand" href="#" style="text-transform: uppercase;"> Upload Image </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item active"> </li> <a class="dropdown-item" href="/ImageUpload/AddImageCtl">Add Image</a> <a class="dropdown-item" href="/ImageUpload/ImageListCtl">View Image</a> <%-- <a class="dropdown-item" href="<%=ONWview.Add_News_category_list_Ctl%>">View Image</a> --%> </div> </nav> </body> </html>
AddImage.jsp
<%@page import="com.imageModel.java.AddImageCtl"%> <head> <title></title> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <!-- JavaScript Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto+Slab&display=swap" rel="stylesheet"> <style type="text/css"> .container{ border: 2px solid #fff; background: #fff; border-radius:5px; width: 50%; } textarea { width: 100%; height: 150px; padding: 12px 20px; box-sizing: border-box; border: 2px solid #ccc; border-radius: 4px; background-color: transparent; font-size: 16px; resize: none; } h1,label{ font-family: 'Roboto Slab', serif; } a{ font-size: 20px; text-decoration: none; color: #D66D75; padding: 10px 10px ; background-color:#fff; border-radius:5px; font-size: larger; } button[type=submit] { background-color: #D66D75; border-radius:5px; font-size: larger; } </style> <%@include file="Header.jsp"%> </head> <body style="background: gray;"> <div class="container mt-3"> <form action="/ImageUpload/AddImageCtl" method="post" enctype="multipart/form-data"> <jsp:useBean id="bean" class="com.imageModel.java.ImageBean" scope="request"></jsp:useBean> <span style="color: #000; font-style: inherit; font-weight: bolder;"></span> <div class="row"> <div class="col-2"></div> <div class="col-8"> <label>Name</label><input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Enter Image Name" name="name"> </div><br> <center> <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label"> Select Image: </label> <input type="file" id="exampleFormControlInput1" placeholder="" name="uplodeimage"> </div> </center> <div class="container text-center"> <input type="submit" class="btn btn-success btn-lg mb-1" name="operation" value="Save" style="align-self:"></div> <div class="col-2"></div> </form> </body> <div> </html>
Imageview.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@page import="java.util.Iterator"%> <%@page import="com.imageModel.java.ImageListCtl"%> <%@page import="com.imageModel.java.ImageModel"%> <%@page import="java.util.List"%> <%@page import="com.imageModel.java.ImageBean"%> <!DOCTYPE html> <html> <head> <style> </style> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> <!-- JavaScript Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <meta charset="ISO-8859-1"> <title>UserList</title> </head> <body style="background-color: gray;"> <%@include file="Header.jsp"%> <br> <br> <tr> <% List list = (List) request.getAttribute("list"); %> </tr> <br> <table class="table table-striped"> <tr> <th scope="col" class="w3-ul w3-Black">Name</th> <th scope="col" class="w3-ul w3-Black">Image</th> </tr> <% int index = 1; Iterator it = list.iterator(); while (it.hasNext()) { ImageBean bean = (ImageBean) it.next(); %> <tr> <td class="w3-ul w3-gray"><%=bean.getName()%></td> <td><img src="/ImageUpload/imageCtl?oid=<%=bean.getId()%>" alt="Not found" width="100" height="100"></td> <br> <br> </div> <% } %> </tbody> </table> </form> </body> </html>
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <%@include file="/Header.jsp"%> </body> </html>