Open In App

Employee Management System using Spring Boot

Last Updated : 17 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Employee Management System includes operations like adding new Employees into the Database, updating existing Employees, Delete Employees, Retrieving All Employees’ Data in the form of a Table and the final one is Delete All Employees. In This Article, we will learn about Employee Management systems such as EMS App or EMS. Mostly This Spring boot web application handles the Employee data and performs different operations on each Employee record in the database.

Prerequisites:

To understand this Employee Management System application, you need basic knowledge of below technologies:

  • Spring Boot
  • Thymeleaf
  • MongoDB
  • Other Spring MVC Patterns
  • Bootstrap Framework

The Spring Boot is used for creating web applications with MVC pattern, Thymeleaf is used for generating dynamic HTML content in the web pages as well and the main purpose is integrating the HTML pages with Spring framework, and MongoDB is used for Data Storage.

Employee Data

In this Employee Management System Application, we collected Employee data with different fields like,

  • Employee ID
  • Employee Name
  • Employee Phone Number
  • Employee Gender
  • Employee Salary in Rupees
  • Employee Role

One more thing is the Employee ID is Dynamically Created and Map with other employee details and inserted into the database. In the Employee Management System, we have used the Bootstrap framework for responsive web designing and used models. The Bootstrap Model is Dynamic html Content, when clicking on the button dynamically the Model is Opened.

In this Web Application we can delete an employee by entering employee id and we can update an employee by providing new details of employee with existing employee id and other feature is we can able delete all the employees by entering yes, if you enter yes, the application decides to need to delete all the employee data. Now we will do these all things with coding for better understanding.

Requirements

  • Spring Boot
  • Thymeleaf ( reference )
  • MongoDB
  • Bootstrap
  • Knowledge about Spring MVC
  • Gradle
  • Spring Tool Suite IDE

Project Steps:

  1. Create a Spring Stater Project ( reference )
  2. create packages for controller, pojo, repository in main application package.
  3. In controller package create one EmployeeController class after that create an Employee POJO class in pojo package, after that create one EmployeeRepo Interface in repo package. After that create one html page in templates which is placed in project resource folder.
  4. Now Implement the Controller layer code, after that pojo class and other one interface also we need to implement.
  5. Once completed the back-end functionalities, then develop the Front-End web pages.
  6. After that Integrate both Back-End and Front-End by using Thymeleaf
  7. After that Run the entire project as Spring Boot App ( reference )

Project Dependencies:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}


Note: These Project Dependencies are available in build.gradle file once project is created. For this Project I used these Dependencies.

Project Folder Structure:

project-structure

Now I Will explain the coding part in different layers like Controller layer, Repository, POJO classes and other things. First we start with actual requirement, That is perform some operations on employee details. Before performing operation on employee details first we need employee details right. So I gather some details for employee like Employee ID, Employee Name, Employee Name, Employee Phone Number, Employee Gender, Employee Salary in Rupees And the last one Employee Role all these things. Now declare these fields in POJO class for performing setters and getters operations for every field.

Database Connection

In Spring boot, one file is there that is application.properties file which is used for database connection in this project. In this Project I used MongoDB. Based on that I write some properties in this file for database connection. You can observe that file in the above project folder structure picture.

# database properties
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=ems

# thymeleaf configuration
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html


Model Layer

The Employee.java and ConfirmationForm.java comes under Model Layer which is used to controller the data flow in the application using these pojo classes in this project.

Employee.java

Employee.java is the class which contains all the details of employee and setters and getters methods for every field in the Employee java class as well as parameterized constructor and one default constructor I used in this POJO for different operations like data insertion and data update and data delete and others. And one dependency is available in spring boot that is lombok.

Java




package com.ems.app.pojo;
  
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
  
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "employee")
public class Employee {
  
    @Id private String id;
    private String employeeName;
    private String employeeEmail;
    private Long employeePhone;
    private String employeeGender;
    private String employeeSalary;
    private String employeeRole;
}


It is provide lot annotations but in this pojo I used @Data, @AllArgsConstructor, @NoArgsConstructor, @Document(collection=”employee)”. The @Data annotation is used for managing setters and getters methods as well as @AllArgsConstructor is used for managing parameterized constructor and @NoArgsConstructor is used for managing default constructor, @Document(collection=”employee) is used for creating document in MongoDB.

ConfirmationForm.java

This Pojo class is used for conformation to delete all the employee’s data by typing ‘yes’ in the text filed. If You Enter Yes in that text field, you conformed to delete all employee’s data from the database. I will explain about this pojo class in controller layer for better understanding.

Java




package com.ems.app.pojo;
  
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
  
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ConfirmationForm {
    private String confirmation;
}


View

Generally the HTML, JSP, and other front-end technologies are comes under View layer in Spring MVC. For this Employee Management System I used HTML as a View for displaying the Data to end users with the help of Thymeleaf. In this HTML page I created four Dynamic forms for handling the Application from front-end. every page performs a unique operation based on its use.

index.html

HTML




<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  
<head>
    <link rel="shortcut icon" href="https://cdn-icons-png.flaticon.com/512/470/470199.png">
    <meta charset="UTF-8">
    <title>EMS App</title>
</head>
  
<style>
    body {
        overflow-x: hidden;
        scroll-behavior: smooth;
    }
  
    nav {
        background-color: navy !important;
  
    }
  
    .navbar-brand {
        color: whitesmoke !important;
        font-size: 30px !important;
        font-weight: bold;
    }
  
    .card {
        box-shadow: rgba(14, 30, 37, 0.12) 1px 2px 2px 0px, rgba(14, 30, 37, 0.32) 1px 2px 2px 0px;
    }
  
    .card-body {
        text-align: center;
    }
  
    .table-responsive {
        box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 2px 6px 2px;
    }
  
    th {
        text-align: center;
        font-size: 18px !important;
    }
  
    td {
        text-align: center;
        font-size: 15px;
        font-weight: 500;
    }
  
    label {
        font-weight: 500;
    }
</style>
  
<body>
  
    <nav class="navbar navbar-expand-sm navbar-light mb-5">
        <div class="container">
            <a class="navbar-brand text-bold" href="#"><i class="fa fa-align-center"
                    aria-hidden="true">  EMS</i></a>
        </div>
    </nav>
  
    <main>
        <div class="container p-4">
            <div class="head_section">
                <div class="row row-cols-1 row-cols-md-4 g-3">
                    <div class="col">
                        <a href="#exampleModalToggle1" data-bs-toggle="modal" role="button"
                            style="text-decoration: none; color: white;">
                            <div class="card h-100 bg-success">
                                <div class="card-body">
                                    <h5 class="text-light"><i class="fa fa-plus"></i> Add Employee</h5>
                                </div>
                            </div>
                        </a>
                    </div>
                    <div class="col">
                        <a href="#exampleModalToggle2" data-bs-toggle="modal" role="button"
                            style="text-decoration: none; color: white;">
                            <div class="card h-100 bg-primary">
                                <div class="card-body">
                                    <h5 class="text-light"><i class="fa fa-area-chart"
                                            aria-hidden="true"></i> Update Employee</h5>
                                </div>
                            </div>
                        </a>
                    </div>
                    <div class="col">
                        <a href="#exampleModalToggle3" data-bs-toggle="modal" role="button"
                            style="text-decoration: none; color: white;">
                            <div class="card h-100 bg-danger">
                                <div class="card-body">
                                    <h5 class="text-light"><i class="fa fa-trash"></i> Delete Employee</h5>
                                </div>
                            </div>
                        </a>
                    </div>
                    <div class="col">
                        <a href="#deleteAllModal4" data-bs-toggle="modal" role="button"
                            style="text-decoration: none; color: white;">
                            <div class="card h-100 bg-dark">
                                <div class="card-body">
                                    <h5 class="text-light"><i class="fa fa-warning"></i> Delete All</h5>
                                </div>
                            </div>
                        </a>
                    </div>
                </div>
            </div>
            <br>
            <div class="items_table mt-5 mb-4">
                <div class="table-responsive p-2">
                    <h4 class="text-center p-2 class=" p-1" mt-2"
                        style="font-family:'Times New Roman', Times, serif; font-weight: bold;">Employee Management
                        System</h4>
                    <table class="table table-bordered table-hover mt-5">
                        <thead class="bg-warning">
  
                            <th>SI.NO</th>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Gender</th>
                            <th>Salary</th>
                            <th>Role</th>
  
                        </thead>
                        <tbody>
                            <tr th:each="employee, index : ${employees}">
                                <td th:text="${index.index + 1}"></td>
                                <td th:text="${employee.id}"></td>
                                <td th:text="${employee.employeeName}"></td>
                                <td th:text="${employee.employeeEmail}"></td>
                                <td th:text="${employee.employeePhone}"></td>
                                <td th:text="${employee.employeeGender}"></td>
                                <td th:text="${employee.employeeSalary}"></td>
                                <td th:text="${employee.employeeRole+' Developer'}"></td>
                            </tr>
  
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>
  
  
    <!-- model for create-->
    <div class="modal fade" id="exampleModalToggle1" aria-hidden="true" aria-labelledby="exampleModalToggleLabel"
        tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-body">
                    <div th:if="${success}" class="alert alert-success" role="alert">
                        <p th:text="${success}"></p>
                    </div>
                    <form class="p-2" th:action="@{/create}" th:object="${employee}" method="post">
                        <center>
                            <h4 style="font-family: 'Times New Roman', Times, serif;">Add Employee</h4>
                        </center>
  
                        <div class="row p-2">
                            <label class="p-1" for="employeeName">Employee Name</label>
                            <input type="text" th:field="*{employeeName}" class="form-control"
                                placeholder="employee name" required>
                        </div>
  
                        <div class="row p-2">
                            <label class="p-1" for="employeeEmail">Email</label>
                            <input type="text" th:field="*{employeeEmail}" class="form-control"
                                placeholder="email address" required>
                        </div>
  
                        <div class="row p-2">
                            <label class="p-1" for="employeePhone">Phone</label>
                            <input type="tel" th:field="*{employeePhone}" class="form-control"
                                placeholder="phone number" required>
                        </div>
  
                        <div class="row p-2">
                            <label class="p-1">Gender</label>
                            <select th:field="*{employeeGender}" class="form-select" required>
                                <option value="" selected>select option</option>
                                <option value="Male">Male</option>
                                <option value="Female">Female</option>
                            </select>
                        </div>
  
                        <div class="row p-2">
                            <label class="p-1" for="employeeSalary">Phone</label>
                            <input type="number" th:field="*{employeeSalary}" class="form-control" placeholder="salary"
                                required>
                        </div>
  
                        <div class="row p-2">
                            <label class="p-1" for="employeeRole">Employee Role</label>
                            <select th:field="*{employeeRole}" class="form-select" required>
                                <option value="" selected>select option</option>
                                <option value="Java">Java Developer</option>
                                <option value="Python">Python Developer</option>
                                <option value="Web">Web Developer</option>
                                <option value="Android">Android Developer</option>
                                <option value="UI">UI Developer</option>
                            </select>
                        </div>
  
                        <button type="submit" class="btn btn-success mt-3 mb-2">Add Employee</button>
                    </form>
                </div>
  
            </div>
        </div>
    </div>
    </div>
  
  
    <!-- model for update-->
    <div class="modal fade" id="exampleModalToggle2" aria-hidden="true" aria-labelledby="exampleModalToggleLabel"
        tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-body">
                    <form class="p-2" th:action="@{/update}" th:object="${employee}" method="post">
                        <!-- Check if errorMessage is present in the model and display it -->
                        <div th:if="${errorMessage}" class="alert alert-danger" role="alert">
                            <p th:text="${errorMessage}"></p>
                        </div>
  
                        <center>
                            <h4 style="font-family: 'Times New Roman', Times, serif;">Update Employee</h4>
                        </center>
  
                        <div class="row p-1">
                            <label class="p-1" for="id">Employee ID</label>
                            <input type="text" th:field="*{id}" class="form-control" placeholder="employee id" required>
                        </div>
  
                        <div class="row p-1">
                            <label class="p-1" for="employeeName">Employee Name</label>
                            <input type="text" th:field="*{employeeName}" class="form-control"
                                placeholder="employee name" required>
                        </div>
  
                        <div class="row p-1">
                            <label class="p-1" for="employeeEmail">Email</label>
                            <input type="text" th:field="*{employeeEmail}" class="form-control"
                                placeholder="email address" required>
                        </div>
  
                        <div class="row p-1">
                            <label class="p-1" for="employeePhone">Phone</label>
                            <input type="tel" th:field="*{employeePhone}" class="form-control"
                                placeholder="phone number" required>
                        </div>
  
                        <div class="row p-1">
                            <label class="p-1">Gender</label>
                            <select th:field="*{employeeGender}" class="form-select" required>
                                <option value="" selected>select option</option>
                                <option value="Male">Male</option>
                                <option value="Female">Female</option>
                            </select>
                        </div>
  
                        <div class="row p-1">
                            <label class="p-1" for="employeeSalary">Phone</label>
                            <input type="number" th:field="*{employeeSalary}" class="form-control" placeholder="salary"
                                required>
                        </div>
  
                        <div class="row p-1">
                            <label class="p-1" for="employeeRole">Employee Role</label>
                            <select th:field="*{employeeRole}" class="form-select" required>
                                <option value="" selected>select option</option>
                                <option value="Java">Java Developer</option>
                                <option value="Python">Python Developer</option>
                                <option value="Web">Web Developer</option>
                                <option value="Android">Android Developer</option>
                                <option value="UI">UI Developer</option>
                            </select>
                        </div>
  
                        <button type="submit" class="btn btn-primary mt-3 mb-2">Update Employee</button>
                    </form>
                </div>
  
            </div>
        </div>
    </div>
    </div>
  
  
    <!-- model for delete-->
    <div class="modal fade" id="exampleModalToggle3" aria-hidden="true" aria-labelledby="exampleModalToggleLabel"
        tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-body">
                    <form class="p-2" th:action="@{/remove}" th:object="${employee}" method="post">
                        <!-- Alert message -->
                        <div th:if="${alertMessage}" class="alert alert-danger">
                            <p th:text="${alertMessage}"></p>
                        </div>
  
                        <center>
                            <h4 style="font-family: 'Times New Roman', Times, serif;">Delete Employee</h4>
                        </center>
  
                        <div class="row p-2">
                            <label class="p-1" for="id">Employee ID</label>
                            <input type="text" th:field="*{id}" class="form-control" placeholder="employee id" required>
                        </div>
  
                        <button type="submit" class="btn btn-danger mt-3 mb-2">Delete Employee</button>
                    </form>
  
                </div>
  
            </div>
        </div>
    </div>
    </div>
  
    <!-- Delete All employees-->
    <div class="modal fade" id="deleteAllModal4" aria-hidden="true" aria-labelledby="deleteAllModalLabe4" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-body">
                    <form class="p-2" th:action="@{/remove/all}" th:object="${confirmationForm}" method="post">
                        <center>
                            <h4 style="font-family: 'Times New Roman', Times, serif;">Delete All Employees</h4>
                        </center>
  
                        <div class="row p-2">
                            <label class="p-3 text-warning" for="confirmation">Type 'Yes' For Confirmation</label>
                            <input type="text" th:field="*{confirmation}" class="form-control"
                                placeholder="confirmation" required>
                        </div>
  
                        <button type="submit" class="btn btn-dark mt-3 mb-2">Delete All Employees</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
  
  
    <!-- bootstrap js -->
</body>
  
</html>


In above HTML code I attached Thymeleaf URL to HTML element. And the main thing is for every form in th:acton attribute I provide the Controller Handlers based on the Logic. Now The Thymeleaf Will take care of it.

Repository

In this Project I created one Mongo Repository for performing CRUD operations. @Repository is used for creating Mongo Repository. And it is possible to use all CRUD Operations by using java interface. This interface is extends to Mongo Repository.

Java




package com.ems.app.repo;
  
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
  
import com.ems.app.pojo.Employee;
  
@Repository
public interface EmployeeRepo extends MongoRepository<Employee, String>{
  
}


In above code I created one interface that is EmployeeRepo which extends to MongoRepository. I used MongoDB that’s why here I used Mongo Repository, For other databases It is different one more thing is the MongoRepository takes two arguments namely first one is name of the POJO class, for performing operation on It. The Second one is Datatype of the id in POJO class. In my Employee pojo I declared id as String datatype because the employee id contains both letters and digits. This EmployeeRepo interface is used for insert, delete, update, retrieve of data.

Controller Layer

The Controller layer is created by using @Controller annotation in Spring boot. The Controller class is used for processing the incoming API requests, And Preparing the Model and returning the view to be rendered as a response. In this Controller class I create entire project logic here. I will explain each and every thing in this layer by dividing them into small pieces.

EmployeeController.java

Java




package com.ems.app.controller;
  
import java.util.List;
import java.util.Optional;
import java.util.Random;
  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
  
import com.ems.app.pojo.ConfirmationForm;
import com.ems.app.pojo.Employee;
import com.ems.app.repo.EmployeeRepo;
  
@Controller
public class EmployeeController {
  
    @Autowired
    private EmployeeRepo employeeRepo;
  
    // display the html page
    @GetMapping("/")
    public String getIndex(Model model) {
        List<Employee> employeeList = employeeRepo.findAll();
        model.addAttribute("employees", employeeList);
        model.addAttribute("employee", new Employee());
        model.addAttribute("confirmationForm", new ConfirmationForm());
        return "index";
    }
  
    // Insert employee data
    @PostMapping("/create")
    public String newEmployee(Employee employee, Model model) {
        model.addAttribute("employee", new Employee());
  
        // creating dynamic Employee ID
        String empId = "EMP";
        Random random = new Random();
        long randomNumber = 1000 + random.nextInt(9000);
        empId = empId + randomNumber;
        employee.setId(empId);
  
        // save the employee
        employeeRepo.save(employee);
  
        return "redirect:/";
    }
  
    // update the existing employee
    @PostMapping("/update")
    public String updateEmployee(@ModelAttribute Employee employee, Model model) {
        model.addAttribute("employee", new Employee());
        Optional<Employee> existingEmployee = employeeRepo.findById(employee.getId());
  
        // checking employee exist or not
        if (existingEmployee.isPresent()) {
            employeeRepo.save(employee);
        } else {
            model.addAttribute("errorMessage", "Employee with ID " + employee.getId() + " not found.");
        }
        return "redirect:/";
    }
  
    // delete an employee by id
    @PostMapping("/remove")
    public String removeEmployee(Employee employee, Model model) {
        model.addAttribute("employee", new Employee());
        Optional<Employee> existingEmployee = employeeRepo.findById(employee.getId());
        if (existingEmployee.isPresent()) {
            employeeRepo.deleteById(employee.getId());
        }
        return "redirect:/";
    }
  
    // delete all employees data by confromation
    @PostMapping("/remove/all")
    public String removeAll(@ModelAttribute ConfirmationForm confirmationForm, Model model) {
        String confirmation = confirmationForm.getConfirmation();
        if ("Yes".equalsIgnoreCase(confirmation)) {
            employeeRepo.deleteAll();
        } else {
            return "redirect:/";
        }
        return "redirect:/";
    }
  
}


In above code I implemented different handlers for different purposes. Here Handler means Request URL. In this I used more then 3 handlers below I listed those.

  • @GetMapping(“/”) this handler is used for display the html page
  • @PostMapping(“/create”) this handler is used for insert employee data
  • @PostMapping(“/update”) this handler is used for update an existing employee by using employee id
  • @PostMapping(“/remove”) this handler is used for delete an employee by using employee id
  • @PostMapping(“/remove/all”) this handler is used for delete all employees details by providing conformation

And also I used EmployeeRepo here for performing the back-end operations by using it’s object.

Display HTML Page

For Displaying HTML page I used Thymeleaf for rendering purpose. For this I created one GET Handler which is used for GET Request which working as HTTP GET method.

Java




@GetMapping("/")
    public String getIndex(Model model) {
        List<Employee> employeeList = employeeRepo.findAll();
        model.addAttribute("employees", employeeList);
        model.addAttribute("employee", new Employee());
        model.addAttribute("confirmationForm", new ConfirmationForm());
        return "index";
    }


Output screen of Index Page:

Index Page for Employee Management System

In above piece of code I created one method which is type String. After that I passed Model class as argument to this method. This Model class is used for creating model attributes which are used for rendering the View in the HTML content. After that I create one list for gathering all employees data by using EmployeeRepo Object. In this Object I used findAll() which is used for get all employee data. After that Created one employees model attribute for employeeList. This employees model attribute is send to html page by using Model after that In HTML page the Thymeleaf hold this attribute and display the data in the form Table. And I created One more Model Attribute that is employee which is used for handling the employee pojo class from Thymeleaf Side. And finally I return the index page for this method.

Insert Employee Data

For Inserting Employee data into database I used EmployeeRepo object which provides save() methods which is used for saving employee data into database.

Java




@PostMapping("/create")
    public String newEmployee(Employee employee, Model model) {
        model.addAttribute("employee", new Employee());
        // creating dynamic Employee ID
        String empId = "EMP";
        Random random = new Random();
        long randomNumber = 1000 + random.nextInt(9000);
        empId = empId + randomNumber;
        employee.setId(empId);
        // save the employee
        employeeRepo.save(employee);
        return "redirect:/";
    }


Output screen of Insert Employee:

Insert Employee in Database

Here I created A POST mapping because I this method I send data into database that’s why I used post mapping here. As well as I created a model attribute for handling employee pojo in the HTML page using Thymeleaf. After I created a random Employee id by using Random class in Java. For Random ID, I take EMP as prefix of the Employee ID, After that dynamically generate 4 Digit number then con-cat both of them. After successfully generating Employee ID Set this value to id in Employee pojo class by using setId ()method. After that I save the employee data into database. In HTML page created one form for gathering employee data. After Successfully insert employee data that will displayed in the Table.

Update Employee Data

If you want to update an employee, you need existing employee ID then we can update employee data other wise not possible. It is a same Inserting data but Before inserting in this method I check if employee id exist or not. If exist I give Access to update employee information.

Java




@PostMapping("/update")
    public String updateEmployee(@ModelAttribute Employee employee, Model model) {
        model.addAttribute("employee", new Employee());
        Optional<Employee> existingEmployee = employeeRepo.findById(employee.getId());
  
        // checking employee exist or not
        if (existingEmployee.isPresent()) {
            employeeRepo.save(employee);
        } else {
            model.addAttribute("errorMessage", "Employee with ID " + employee.getId() + " not found.");
        }
        return "redirect:/";
    }


Output screen of Update Employee Details:

Updating Employee Information in System

After Successful Employee details update redirect to Index page and the is visible in the table. For I used Post Mapping means I Posting the data that’s why I use this mapping. It is possible using Thymeleaf in HTML page.

Delete Employee Data

For Deleting an Employee, we need Employee ID, then only we can be able to delete an existing employee otherwise it’s not possible to delete. After Successful delete, the result is updated in Employee table for this I used Thymeleaf for handling the Employee pojo class. For this used post mapping for comparing employee id with employee data.

Java




@PostMapping("/remove")
    public String removeEmployee(Employee employee, Model model) {
        model.addAttribute("employee", new Employee());
        Optional<Employee> existingEmployee = employeeRepo.findById(employee.getId());
        if (existingEmployee.isPresent()) {
            employeeRepo.deleteById(employee.getId());
        }
        return "redirect:/";
    }


Output screen of Delete Employee:

Delete Employee from the Database

After Providing the An Employee ID click on the given button This button triggers the Thymeleaf. The Thymeleaf will perform operation on employee model attribute. This Employee Attribute is created on Controller class. In this Controller class Deletion operation performed using EmployeeRepo object after successfully deleting the employee this result is updated in Employee Table.

Delete All Employees

The Delete All employee’s logic is working based on user conformation. The Conformation is nothing but while before deleting all data the application asks your conformation, if you type yes in the given text field means your conformed to delete all employee’s data. From HTML page side the Thymeleaf is perform this by holding ConfirmationForm pojo. This ConfirmationForm is accepting a String. if That string is matches with yes then deleted all data automatically.

Java




@PostMapping("/remove/all")
    public String removeAll(@ModelAttribute ConfirmationForm confirmationForm, Model model) {
        String confirmation = confirmationForm.getConfirmation();
        if ("Yes".equalsIgnoreCase(confirmation)) {
            employeeRepo.deleteAll();
        } else {
            return "redirect:/";
        }
        return "redirect:/";
    }


Output Screen of Delete all Employees:

Delete All Employee Details

While click on Delete All button index page this form will open dynamically. If you enter Yes in that text field That means Your conformed delete all employees. After That Will be triggered on both HTML page and MongoDB also. After Delete All Employees the HTML page Look like below mentioned picture:

After Deleting All Employees



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads