Upload images to database and Display Images on JSP page dynamically using JSP & Servlet with source code

Upload Image to a database and Display Image on JSP page dynamically using JSP & Servlet.

For a complete tutorial on How to Upload images to the database and Display Images on the JSP page dynamically using JSP & Servlet?

PROGRAM TO Upload Images to the database and Display Images on the JSP page dynamically using JSP & Servlet.

SOURCE CODE :

addImage.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>Add Image</title>
</head>
<body>
<h1 style="color:red" align="center">ADD IMAGE DETAIL</h1>

<div align="center">

<form action="AddImage" method="post" enctype="multipart/form-data">
   Select Image :
   <input type="file" name="image">
   <input type="submit" value="Add Image">
</form>

</div>

</body>
</html>

AddImage.java (Servlet)

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
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;

@MultipartConfig
@WebServlet("/AddImage")
public class AddImage extends HttpServlet {
private static final long serialVersionUID = 1L;
       
    public AddImage() {
        super();
    }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("In do post method of Add Image servlet.");
Part file=request.getPart("image");
String imageFileName=file.getSubmittedFileName();  // get selected image file name
System.out.println("Selected Image File Name : "+imageFileName);
String uploadPath="C:/Users/Vostro.MURADALIMJ/Desktop/Youtube Tutorials/ImageTutorial/WebContent/images/"+imageFileName;  // upload path where we have to upload our actual image
System.out.println("Upload Path : "+uploadPath);
// Uploading our selected image into the images folder
try
{
FileOutputStream fos=new FileOutputStream(uploadPath);
InputStream is=file.getInputStream();
byte[] data=new byte[is.available()];
is.read(data);
fos.write(data);
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
}
//**********************
//getting database connection (jdbc code)
Connection connection=null;
try 
{
Class.forName("com.mysql.cj.jdbc.Driver");
connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/imageTutorial","root","your password");
PreparedStatement stmt;
String query="insert into image(imageFileName) values(?)";
stmt=connection.prepareStatement(query);
stmt.setString(1,imageFileName);
int row=stmt.executeUpdate(); // it returns no of rows affected.
if(row>0)
{
System.out.println("Image added into database successfully.");
}
else
{
System.out.println("Failed to upload image.");
}
}
catch (Exception e)
{
System.out.println(e);
}
}

}

displayImage.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>Display Image</title>
</head>
<body>
<h1 style="color:red" align="center">DISPLAY IMAGE DETAIL</h1>

<div align="center">

<form action="DisplayServlet" method="post">
   Enter Image Id :
   <input type="number" name="imageId">
   <input type="submit" value="Display Image">
</form>

</div>

<hr>

<%
    String imgFileName=(String)request.getAttribute("img");
    String imgId=(String)request.getAttribute("id");
    System.out.println(imgFileName);
%>

<div align="center">
     <table border="5px" style="width:600px">
          <tr>
              <th>Image Id </th>
              <th>Image</th>
          </tr>
         
         <%
             if(imgFileName!="" && imgId!="")
             {
         %>
          
          <tr>
              <td><%=imgId %></td>
              <td><img src="images/<%=imgFileName%>" style="width:300px;height:250px"></td>
          </tr>
        <%
             }
        %>  
     </table>
</div>

</body>
</html>

AddImage.java (Servlet)

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
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;

@WebServlet("/DisplayServlet")
public class DisplayServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
  
    public DisplayServlet() {
        super();
    }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("In do post method of Display Image servlet.");
String imageId=request.getParameter("imageId");
int id=Integer.parseInt(imageId);
//getting database connection (jdbc code)
Connection connection=null;
int imgId=0;
String imgFileName=null;
try 
{
Class.forName("com.mysql.cj.jdbc.Driver");
connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/imageTutorial","root","your password");
Statement stmt;
String query="select * from image";
stmt=connection.createStatement();
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
if(rs.getInt("imageId")==id)
{
imgId=rs.getInt("imageId");
imgFileName=rs.getString("imageFileName");
}
}
}
catch (Exception e)
{
System.out.println(e);
}
RequestDispatcher rd;
request.setAttribute("id",String.valueOf(imgId));  //valueOf
request.setAttribute("img",imgFileName);
rd=request.getRequestDispatcher("displayImage.jsp");
rd.forward(request, response);

}

}


IMAGE REFERENCED IN THE VIDEO FOR EXPLAINING THE CONCEPTS.


Other practical projects using React & Spring Boot 

1) Employee Management System using Spring Boot Microservices & React.

2) Hotel Management System using Spring Boot & React.

3) E-commerce Project using Spring Boot & React.

4) Gym Management System using Spring Boot & React.

Students can use this project for learning and can submit the project for their final year or Internship projects.

IF YOU WANT THE PROJECT DO CONTACT ME. 

I will give you the full project SOURCE CODE and I will do a COMPLETE SET-UP of the project on your PC or Laptop remotely.

Or You can simply Request for the Project Source Code & Set Up by clicking on the below button.

MAIL ME AT codewithmurad@gmail.com

DM ME ON INSTAGRAM at @codewithmurad

DM ME ON FACEBOOK at @codewithmurad 

DM ME ON TELEGRAM at @codewithmurad 

Connect on My Discord Server: CLICK HERE

Post a Comment

1 Comments

  1. Here are two files named AddImage.java (Servlet). And i suppose you are mistaken with the last filename as DisplayServlet. Please do make changes as its confusing.

    ReplyDelete