Edit Employee Details Using Servlet. JAVA CRUD

Hello readers how are you doing? In the last article, I have started a simple Java Servlet project on Employee Management System. This is the 2nd part of the Employee Management System. In this article, I’m going to explain how you can read all the data from the database and show those data in an HTML file.

To show all the data I’m using the Bootstrap table and that table rows will grow dynamically according to the number of records present on the Database. Here I have shown options for delete and update. Update and Delete will discuss on Upcoming articles.

What is CRUD:

In a database we mainly perform Create, Read, Update and Delete operations. These operations are basically called CRUD operations in short.

  • CreateThis operation is used to insert data into the database.
  • Read – is Used to fetch the data from Database.
  • Update – This Operation is used to update data on the database or make changes to the existing Data.
  • Delete – Last operation is Delete, is used to delete data prom database.

Each of the operations has its own query to perform their respective tasks.

The syntax for Reading Data from Database:

Geeksteps DB

We use Select keyword at the end of the query to get the data from the Database. And we can also use where a condition for some specific search.

Select * from table_name;

Or

Select * from table_name where condition;

Example:

Select * from employee;

Or

Select * from employee where id = 1;

I hope you understand the concept of Reading data from Database. You have the project ready and you understood the concept of reading data then let’s create the Servlet class.

Add a Method in EmployeeMain.java

In the previous article, we created a controller class which contains all the MySQL DB connection related codes. Now open the EmployeeMain.java file and paste the below code before closing the final brackets.

public static List<Employee> getAllEmployees(){  
	        List<Employee> list=new ArrayList<Employee>();  
	          
	        try{  
	            Connection con=EmployeeMain.getConnection();  
	            PreparedStatement ps=con.prepareStatement("select * from geeksteps.employee");  
	            ResultSet rs=ps.executeQuery();  
	            while(rs.next()){  
	                Employee e=new Employee();  
	                e.setId(rs.getInt(1));  
	                e.setName(rs.getString(2));  
	                e.setEmail(rs.getString(3));
	                e.setContact(rs.getString(4));  
	                e.setPassword(rs.getString(5));  
	                
	                list.add(e);  
	            }  
	            con.close();  
	        }catch(Exception e){e.printStackTrace();}  
	          
	        return list;  
	    }  

We are adding a method  getAllEmployees() that will store all the data which will be fetched from the database into a List.  Later by calling the method in ViewEmployeeServlet, we can display the records in the HTML file.

Creating Servlet:

Create a servlet class inside your package and save the file as ViewEmployeeServlet.java. This file contains the code of creating a dynamic table according to the number or present in the database.

Here I used Bootstrap for styling the table. On this page, I have enabled Edit and delete Icon but code is not written so it will not work. Edit and Update operations will be discussed in upcoming articles.

Copy the below code and paste it into ViewEmployeeServlet.java. Make sure that you have an internet connection to see the styles.

package com.geeksteps.employee;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;


@WebServlet("/ViewEmployeesServlet")
public class ViewEmployeesServlet extends GenericServlet {
	private static final long serialVersionUID = 1L;

	
	public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {

		PrintWriter printWriter=response.getWriter();  
		
		printWriter.print("<div class=\"container \" style=\"width:90%; margin-top:2%\">");
		printWriter.print("<img alt=\"GeekSteps\" src=\"22222.png\" class =\"mx-auto d-block\" style = \"margin-bottom:-40px\">\r\n" + 
				"");
		printWriter.print("<form action =\"AddEmployee.html\">");
		printWriter.print("  <button  type=\"submit\" class=\"btn btn-success float-right\" style=\"margin-top:20px\">Add Employee</button>");
		printWriter.print("</form>");
		printWriter.println("<h1>Employees List</h1>");  
	
		
		List<Employee> list=EmployeeMain.getAllEmployees();  
		printWriter.print("<head>");
		
		printWriter.print("<link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css' integrity='sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh' crossorigin='anonymous'>");
		printWriter.print("<script src=\"https://code.jquery.com/jquery-3.4.1.slim.min.js\" integrity=\"sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n\" crossorigin=\"anonymous\"></script>");
		printWriter.print("<script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script>");
		printWriter.print("<script src=\"https://kit.fontawesome.com/b20420d4e6.js\" crossorigin=\"anonymous\"></script>");
		
		
		printWriter.print("</head>");
		printWriter.print("<table class='table table-bordered'>");
		printWriter.print("<thead class='thead-dark'>");
		printWriter.print("<tr><th scope='col'>Id</th><th scope='col'>Name</th><th scope='col'>Email</th>"
				+ "<th scope='col'>Phone </th><th scope='col'>Password</th><th scope='col'>Edit</th><th scope='col'>Delete</th></tr>");
		
		
		for(Employee e:list){
		
		
		
			printWriter.print("<tr><td>"+e.getId()+"</td><td>"+e.getName()+"</td><td>"+e.getEmail()+"</td><td>"+e.getContact()+"</td>"
					+ "<td>"+e.getPassword()+"</td><td><a href='EditServlet?id="+e.getId()+"'><i class=\"fas fa-edit\"></i></a></td> "
							+ "<td><a href='DeleteServlet?id="+e.getId()+"'><i class=\"fas fa-trash-alt\"></i></a></td></tr>");  
			
		}
		
		printWriter.print("</table>");
	printWriter.print("</div>");
		
		
		
	}

}

After running the project when you will click on the view Employees button it will display a table with a list of the employees along with their all details.
You can navigate to add the employee page from view employee page by clicking the Add Employee button that is present in the top right corner.

If you have any problem watch the below video, or download the source code from here.

Conclusion

So I hope you have understood how you can upload data into the database using Java. If you have any problem ask me in the comment section. The source code is provided below.
If you found this article helpful then don’t be cheap to share. See you at the next one.

Till then Happy Coding 😉

Subscribe to GeekSteps

4 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here