How to Upload and Retrieve image with MYSQL database using Servlet and JSP. In this JSP tutorial, we will see How Servlet and JSP Upload images into the MYSQL database and another JSP and Servlet example to Retrieve images from MYSQL using JSP and servlet.
Upload and Retrieve Image in MYSQL Database
Create a pet registration form that would have the functionality of uploading pet images in the MYSQL database and Retrieve uploaded images and display them on the JSP page.
Create Database and table in MYSQL workbench
First, let us create a database “demo1234″ and table using MYSQL Workbench.
Create JSP and Servlet(J2ee) Maven Project
Create a Maven project in Eclipse IDE. Following are steps to create a simple Jsp and Servlet Maven project in Eclipse.
- Open Eclipse.
- Go to File > New > Other > Maven project > Next > Next > select maven.archetype-webapp > Next Enter Artefact Id > Finish.
Now, you will get the project structure. Add packages and files as shown below:
Add MYSQL Maven Dependencies into pom.xml
Add both the MYSQL and Servlet dependency inside the pom.xml file.
<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>
Create a Modal Class
Now, we will create a Model class called pet.java.
package in.codebun.bean; import java.sql.Blob; public class Pet { private int id; private String petName; private String petOwner; private String petBreed; private Blob petPhoto; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPetName() { return petName; } public void setPetName(String petName) { this.petName = petName; } public String getPetOwner() { return petOwner; } public void setPetOwner(String petOwner) { this.petOwner = petOwner; } public String getPetBreed() { return petBreed; } public void setPetBreed(String petBreed) { this.petBreed = petBreed; } public Blob getPetPhoto() { return petPhoto; } public void setPetPhoto(Blob petPhoto) { this.petPhoto = petPhoto; } }
Create Database Connection
DBConnection.java is the database connection class of this application that contains the connection with MYSQL. Read more about Database connectivity in java using JDBC.
package in.codebun.DbConnect; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBConnection { public static Connection getConn() { System.out.println("inside conn"); Connection con = null; String loadDriver = "com.mysql.cj.jdbc.Driver"; // driver name for mysql String dbURL = "jdbc:mysql://localhost:3306/demo1234"; // url of the // database String dbUSERNAME = "root"; // username to coonect db String dbPASSWORD = "root"; // password to connect db try { Class.forName(loadDriver); // load the driver con = DriverManager.getConnection(dbURL, dbUSERNAME, dbPASSWORD);// get // the // connection } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return con; // return the connection obj. } }
Create View
Next, create an index.jsp file inside the src/main/webapp folder.
<html> <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%; } 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> </head> <body style="background: linear-gradient(#D66D75,#E29587)"> <h1 align="center" class="mt-5" style="color: white">Pet Registration Form</h1> <center><a href="viewpets.jsp">View Pets</a></center> <div class="container mt-5"> <form action="PetServlet" method="post" enctype="multipart/form-data"> <span style="color: #000; font-style: inherit; font-weight: bolder;"><%=(request.getAttribute("success") == null) ? "" : request.getAttribute("success")%></span> <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">Pet Name</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Enter Pet Name" name="petName"> </div> <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">Pet Owner</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Enter Pet Owner" name="petOwner"> </div> <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">Pet Breed</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Enter Pet Name" name="petBreed"> </div> <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">Pet Photo</label> <input type="file" id="exampleFormControlInput1" placeholder="Enter Pet Name" name="photo"> </div> <div class="container text-center"> <button type="submit" >Submit</button> </div> </form> </div> </body> </html>
Now, create viewpets.jsp to view all the pets
<%@page import="java.sql.ResultSet"%> <%@page import="java.sql.PreparedStatement"%> <%@page import="in.codebun.DbConnect.DBConnection"%> <%@page import="java.sql.Connection"%> <html> <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; } 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; } </style> </head> <body style="background: linear-gradient(#D66D75,#E29587)"> <h1 align="center" class="mt-5" style="color: white">View All Pets</h1> <center><a href="index.jsp">Add Pets</a></center> <div class="container mt-5"> <form> <table class="table table-bordered"> <thead> <tr> <th scope="col">#</th> <th scope="col">Pet Image</th> <th scope="col">Pet Name</th> <th scope="col">Pet Owner</th> <th scope="col">Pet Breed</th> </tr> </thead> <tbody> <% Connection conn = DBConnection.getConn(); String sql = "SELECT * FROM PETTABLE"; PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while(rs.next()){ %> <tr> <th scope="row"><%=rs.getInt(1) %></th> <td><img src=PetServlet?id=<%=rs.getInt(1)%> alt="image not found" width="100px" height="100px"></td> <td><%=rs.getString(2) %></td> <td><%=rs.getString(3) %></td> <td><%=rs.getString(4) %></td> </tr> <%} %> </tbody> </table> </form> </div> </body> </html>
Create Servlet Class
Now, we have created a Servlet class to handle all the request and response objects.
package in.codebun.ctl; import java.io.IOException; import java.io.InputStream; 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.MultipartConfig; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import com.mysql.cj.protocol.Resultset; import com.mysql.cj.xdevapi.DbDoc; import in.codebun.DbConnect.DBConnection; /** * Servlet implementation class PetServlet */ @MultipartConfig(maxFileSize=16177215) public class PetServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public PetServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/jpeg"); int id = Integer.parseInt(request.getParameter("id")); Connection conn = DBConnection.getConn(); String sql = "SELECT * FROM PETTABLE WHERE ID ='"+id+"'"; PreparedStatement ps; try { ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); if(rs.next()){ byte [] imageData = rs.getBytes("petphoto"); // extract byte data from the resultset.. OutputStream os = response.getOutputStream(); // output with the help of outputStream os.write(imageData); os.flush(); os.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); response.getOutputStream().flush(); response.getOutputStream().close(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String petName = request.getParameter("petName"); String petOwner = request.getParameter("petOwner"); String petBreed = request.getParameter("petBreed"); InputStream inputStream = null ;//input stream of uploaded file Part part = request.getPart("photo"); if(part!=null){ System.out.println(part.getName()); System.out.println(part.getSize()); System.out.println(part.getContentType()); inputStream = part.getInputStream(); } // Now Create a connection and send it to DB... Connection conn = DBConnection.getConn(); String sql = "INSERT INTO PETTABLE (PETNAME,PETOWNER, PETBREED, PETPHOTO) VALUES (?,?,?,?)"; try { PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1,petName); ps.setNString(2, petOwner); ps.setString(3, petBreed); ps.setBlob(4, inputStream); int i = ps.executeUpdate(); if(i > 0){ request.setAttribute("success", "Pet Added Successfully"); request.getRequestDispatcher("index.jsp").forward(request, response); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Insert image into MYSQL database in JSP and Servlet
- Here, the Part class represents a part or form item that was received within a multipart/form-data POST request.
- Now, we get the contents of this part inside the inputstream.
- Next, create a Connection with the database. While inserting data from the form to the database we set the designated parameter to an inputStream object as ps.setBlob(4, inputStream);.
Retrieve image into MYSQL database in JSP and Servlet
- First, set the Content-Type to “image/jpeg”.
- Then, create a Connection with the database and fetch the data from the table based on the id.
- Next, extract byte data from the resultset.
- Now, set the output with the help of the OutputStream object.
- At last, write the byte data to the output stream.
Run the Application
Now, run the application on the server and add the pet information and on the view page, we can see the uploaded image.
Thus, in this way, we upload and retrieve images with the database using servlet/JSP.