Spring Boot MVC Application

We can do multiple things in Spring Boot, here we are going to make CRUD application using Spring.

To start with this project we need to have Spring Boot in our system. We can use spring io (https://start.spring.io/) or directly use Spring Boot to create a project.

Tools used:
- Spring Boot
- Maven Dependencies
- Oracle / MySql as Database
- Bootstrap as frontend

We are going to use the MVC approach to make this CRUD Application.

Project Structure as below:




Now create a new project in Spring Boot.

Step 1: Create a Spring Strater Project.



Step 2: Add Project Name, Artifact, Version. Here you can change the version and packing of the project.




Step 3: Add Maven dependencies - Select Spring Web




Click on the finish.

It will take some time to update the project and set up a blank project for you.

Now we come to our project part to add some maven dependencies in pom.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.5.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>com.example</groupId>
 <artifactId>SpringMVCProject</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>SpringMVCProject</name>
 <description>Demo project for Spring Boot</description>

 <properties>
  <java.version>1.8</java.version>
  <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
 </properties>

 <dependencies>

  <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

</project>

If you need the MySql database in your project then add below dependency in pom.xml.

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

The main point of the project is you need to create each and every file as same as shown in Project Structure.

In Spring Boot, our project starts from SpringMvcProjectApplication.java this file, from where initialization takes place.

Open below file:
SpringMVCProject/src/main/java/com/slashcode/employee/SpringMvcProjectApplication.java

package com.slashcode.employee;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringMvcProjectApplication {

 public static void main(String[] args) {
  SpringApplication.run(SpringMvcProjectApplication.class, args);
 }

}

As you can see the main function defined here.

Now come to our model where we need to define the Employee POJO file.
In Employee Pojo we will have its properties, their respective getters and setters, and constructors as below.
You can add a toString() method as per your requirement.

SpringMVCProject/src/main/java/com/slashcode/employee/model/Employee.java

package com.slashcode.employee.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Employee {
 @Id
 @GeneratedValue
 private int empId;
 private String empName;
 private String deptName;
 
 public Employee() {} 
 public Employee(int empId, String empName, String deptName) {
  super();
  this.empId = empId;
  this.empName = empName;
  this.deptName = deptName;
 }
 public int getEmpId() {
  return empId;
 }
 public void setEmpId(int empId) {
  this.empId = empId;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public String getDeptName() {
  return deptName;
 }
 public void setDeptName(String deptName) {
  this.deptName = deptName;
 }
 @Override
 public String toString() {
  return "Employee [empId=" + empId + ", empName=" + empName + ", deptName=" + deptName + "]";
 } 
}

After Employee Pojo, come to our DAO layer where we are going to interact with Database.
You just need to add @Repository and extends JpaRepository for DAO interface, rest all thing will be taken care internally.
Like all database related queries required for CRUD operations.

SpringMVCProject/src/main/java/com/slashcode/employee/dao/IEmployeeDAO.java


package com.slashcode.employee.dao;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.slashcode.employee.model.Employee;

@Repository
public interface IEmployeeDAO extends JpaRepository<Employee, Integer> {

 List<Employee> findByDeptName(String deptName);
}

So after the DAO layer, we will come to the service layer where all business-related logic takes place.
In the service layer, we will have the Employe Service interface and its implementation as below.

SpringMVCProject/src/main/java/com/slashcode/employee/service/IEmployeeService.java

package com.slashcode.employee.service;

import java.util.List;

import com.slashcode.employee.model.Employee;

public interface IEmployeeService {

 List<Employee> getAllEmployee();
 Employee getEmployeeById(int empId);
 void addEmployee(Employee employee);
 void updateEmployee(Employee employee, int empId);
 void deleteEmployee(int empId);
 List<Employee> getEmployeeByDept(String deptName);
}

SpringMVCProject/src/main/java/com/slashcode/employee/service/EmployeeServiceImpl.java

package com.slashcode.employee.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.slashcode.employee.dao.IEmployeeDAO;
import com.slashcode.employee.model.Employee;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
 @Autowired
 private IEmployeeDAO daoRef;
 
 @Override
 public List<Employee> getAllEmployee() {
  return daoRef.findAll();
 }
 @Override
 public Employee getEmployeeById(int empId) {
  return daoRef.getOne(empId);
 }
 @Override
 public void addEmployee(Employee employee) {
 }

 @Override
 public void updateEmployee(Employee employee, int empId) {
  daoRef.save(employee);
 }

 @Override
 public void deleteEmployee(int empId) {
  daoRef.deleteById(empId);
 }
 @Override
 public List<Employee> getEmployeeByDept(String deptName) {
  return daoRef.findByDeptName(deptName);
 }
}

In the above EmployeeServiceImpl.java file, we have called added IEmployeeDAO using @Autowired annotation so that we can call its functions.
You can see we have added multiple functions that we not even defined the IEmployeeDAO interface. These functions are coming from JpaRepository Interface which we have extended in that.

Now come to the controller part, where all routing going to perform.
On which route which function will get a call, we are going to define them here.

SpringMVCProject/src/main/java/com/slashcode/employee/controller/EmployeeController.java

package com.slashcode.employee.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.slashcode.employee.model.Employee;
import com.slashcode.employee.service.IEmployeeService;

@Controller
public class EmployeeController {

 @Autowired
 IEmployeeService serviceRef;
 
 @RequestMapping("/")
 public String getHomePage(Model model) {
  model.addAttribute("successMsg", "Welcome to My Youtube Channel /Code");
  
  return "Homepage";
 }
 
 @RequestMapping("/addNewEmployee")
 public String addNewEmployeePage(Model model) {
  model.addAttribute("employee",new Employee());
  return "NewEmployee";
 }
 
 
 @RequestMapping("/addEmployeeDetails")
 public String addEmployeeDetails(@ModelAttribute("employee") Employee employee, BindingResult result, Model model){
  
  if(result.hasErrors()){
   return "NewEmployee";
  }
  else{
   serviceRef.addEmployee(employee);
   model.addAttribute("successMsg", "Data Inserted Successfully");
   return "Homepage";
  }
 }
 
 @RequestMapping("/getAllEmployee")
 public String getEmployeeList(Model model) {
  List<Employee> empList = new ArrayList<Employee>();
  empList= serviceRef.getAllEmployee();
  model.addAttribute("employeeList",empList);
  return "employeeview";
 }
 
 @RequestMapping(value="/employee", method=RequestMethod.GET)
 public String Employee(Model model, @RequestParam("empId") int empId) {
  Employee emp  = serviceRef.getEmployeeById(empId);
  model.addAttribute("employeeData",emp);
  return "EmployeeOperation";
 }
 
 @RequestMapping("/updateEmployee")
 public String updateEmployee(Model model, @RequestParam("empId") int empId) {
  Employee emp = serviceRef.getEmployeeById(empId);
  model.addAttribute("employeeDetails", emp);
  return "updateEmployeePage";
 } 
 @RequestMapping("/updateEmployeeDetails")
 public String updateEmployeeDetail(@ModelAttribute("employee") Employee employee, BindingResult result, Model model){
  
  if(result.hasErrors()){
   return "NewEmployee";
  }
  else{
   serviceRef.updateEmployee(employee, employee.getEmpId());
   model.addAttribute("successMsg", "Employee Updated Successfully");   
   return "Homepage";
  }
 }
 
 @RequestMapping("/deleteEmployee")
 public String deleteEmployee(Model model, @RequestParam("empId") int empId) {
  serviceRef.deleteEmployee(empId);
  model.addAttribute("successMsg", "Employee Deleted Successfully");
  return "Homepage";
 } 
}

UI Part we will see in the next part. ( Spring Boot MVC Application - UI )

Youtube video link for your reference.


Comments

Popular posts from this blog

How to read XLS and XLSX Excel files in Java

How to Read CSV File in Java

User Login and Logout with the session