Home TechnologyHTML Java Servlet CRUD: Add Employee

Java Servlet CRUD: Add Employee

by Snehashis Mukherjee
Add-Employee-Using-Servlet-and-MySQL

Hello readers how are you doing? Here I’m starting a simple project of Employee management system using Java, Servlet as backend and HTML and Bootstrap as frontend. This project is to be divided into 4 parts. In this article, I’m going to explain how you can insert data into the database by connecting MySQL DB with Java. This project is developed using the MVC structure. To know more about MVC follow this article.

What is CRUD:

In a database we mainly perform Create, Read, Update and Delete operations. And 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.

MySql DB connection in java

First Open phpMyAdmin create a database called geeksteps and then copy the following code and run on the database.

Database add employee geeksteps
CREATE TABLE `geeksteps`.`employee` ( `id` INT NOT NULL , `Name` VARCHAR(30) NOT NULL , `Email` VARCHAR(30) NOT NULL , `Contact` VARCHAR(10) NOT NULL , `Password` VARCHAR(30) NOT NULL , UNIQUE (`id`)) ENGINE = InnoDB;

The syntax for Inserting Data:

The main work is to insert data into the database. To perform Insert perform we use the INSERT keyword.

insert into ”database name”.”tablename” (“col1”, “col2”,”col3”) values (?,?,?);

Example

insert into geeksteps.employee(name,email,contact,password) values (“Amit”,”abcd@gmail.com”,123467890,”13234”);

Project Creation

In this article, I have explained to you how you can set up a project in eclipse and perform the tasks.
Follow the below steps to complete insert operation

Step 1: Create Frontend

add employee front end

Create an HTML file in Web Content and save the file as AddEmployee.html. After creating copy the below code and paste into the AddEmployee.html.

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity
="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin
="anonymous">
 
<title>GeekSteps Employee Maintenance Service</title>
</head>
<body>
 
 
<div class="container " style="width:50%; margin-top:2%">
<img alt="GeekSteps" src="22222.png" class ="mx-auto d-block" style = "margin-bottom:0px">
 
<h1><strong>Add New Employee</strong></h1>
 
<form action ="AddEmployeeServlet">
 
 <div class="form-group">
    <label for="exampleInputName">Name</label>
    <input type="text" class="form-control" id="exampleInputName" autocomplete="off" name ="name">
  </div>
  
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" autocomplete="off" name = "email">
  </div>
   <div class="form-group">
    <label for="exampleInputPhone">Contact Number</label>
    <input type="Number" class="form-control" id="exampleInputPhone" autocomplete="off" name= "phone">
  </div>
    
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" class="form-control" id="exampleInputPassword1" name = "password">
  </div>
  
  <button type="submit" class="btn btn-success">Add Employee</button>
  
</form>
 
<button type="submit" class="btn btn-info float-right"style="margin-top:-35px">View All Employees</button>
 
</div>
<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>
</body>
</html>

Step 2: Create a Model

Creating the Model of the Project which will contain set() and get() methods. Set() and Get() methods will store all the employee values which we will pass from the web browser. So that values can be used anywhere by calling get() method. Create a Java Class and save the file as Employee.java. Copy the below code and paste it into Employee.java.

package com.geeksteps.employee;
 
public class Employee {
 
 private int id;
 
 private String name, email, password,contact;
 public int getId() {
 return id;
 }
 public void setId(int id) {
 this.id = id;
 }
 public String getContact() {
 return contact;
 }
 public void setContact(String contact) {
 this.contact = contact;
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public String getEmail() {
 return email;
 }
 public void setEmail(String email) {
 this.email = email;
 }
 public String getPassword() {
 return password;
 }
 public void setPassword(String password) {
 this.password = password;
 }
 public static int saveEmp(Employee emp) {
 // TODO Auto-generated method stub
 return 0;
 }
 
}

Step3: Create View

Creating View. This is a servlet class that will help to retrieve data from HTML forms and sent that data to Employee.java. And all the data we can access from anywhere.It also gives the output whether the Employee details are stored in the database or not.

Create a Servlet and save the servlet as AddEmployeeServlet.java. Copy the below code and paste it into the AddEmployeeServlet.java file.

package com.geeksteps.employee;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
 
 
@WebServlet("/AddEmployeeServlet")
public class AddEmployeeServlet extends GenericServlet {
 private static final long serialVersionUID = 1L;
 
 
 public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
 
 PrintWriter printWriter = response.getWriter();
 
 String name=request.getParameter("name");  
     String email=request.getParameter("email"); 
     String phone=request.getParameter("phone"); 
         String password=request.getParameter("password");  
         
         System.out.println(name + " "+ email);
     
         Employee emp = new Employee();
         emp.setName(name);
         emp.setEmail(email);
         emp.setContact(phone);
         emp.setPassword(password);
         
         
         int status=EmployeeMain.saveEmp(emp);  
         if(status>0){  
            printWriter.print("<script>window.alert('Record Updated Successfully')</script>");  
             request.getRequestDispatcher("AddEmployee.html").include(request, response);  
         }else{  
             printWriter.println("<script>window.alert('Sorry Unable to add! Already Employee Exsists')</script>");  
             request.getRequestDispatcher("AddEmployee.html").include(request, response);  
         }  
           
         printWriter.close();  
         
 }
 
}

Step4: Create Controller

Creating the Controller of the Project which will contain java Database connection codes. Create a Java class and save the file as EmployeeMain.java. Copy the below code and paste into EmployeeMain.java.

package com.geeksteps.employee;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
 
public class EmployeeMain {
 
  public static Connection getConnection(){  
         Connection con=null;  
         try{  
          Class.forName("com.mysql.jdbc.Driver"); 
             con=DriverManager.getConnection("jdbc:mysql://localhost:3306?user=root&password=");  
         }catch(Exception e){System.out.println(e);}  
         return con;  
     }  
 
    public static int saveEmp(Employee emp){  
         int status=0;  
         try{  
          String query1 = "insert into geeksteps.employee(name,email,contact,password) values (?,?,?,?)";
          String query2 = "select email from geeksteps.employee where email = ?";
             Connection con=EmployeeMain.getConnection();  
             PreparedStatement ps=con.prepareStatement(query1);  
             ps.setString(1,emp.getName());  
             ps.setString(2,emp.getEmail());   
             ps.setString(3,emp.getContact());   
             ps.setString(4,emp.getPassword());  
           
             
             PreparedStatement ps2=con.prepareStatement(query2); 
             ps2.setString(1, emp.getEmail());
             ResultSet resultSet = ps2.executeQuery();
             
             if(!resultSet.next()) {
              status=ps.executeUpdate();  
             }
               
             
               
             con.close();  
         }catch(Exception ex){ex.printStackTrace();}  
           
         return status;  
     }  
}

After doing all the steps its time to test our code. Don’t worry it will definitely work else if it doesn’t work download the source code from here and watch the below video.

Record Updated Sucessfully

So after filling all the details when you click on the Add Employee button, it will show an alert which will show Employee added Successfully.

If the email address already present in the database then it will check first is the email already present then it will show an alert by saying Unable to add.

Unable to Add User Geeksteps

Conclusion

So I hope you have understood how you can upload data into the database. 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.
Subscribe to GeekSteps
Till then Happy Coding 😉

Related Posts

4 comments

Ankit Kumar December 26, 2019 - 10:00 AM

Very useful tutorial in Java Servelts
It will be helpful for bigginers. 🙂

Reply

Leave a Comment