Tuesday, 26 February 2019

Spring boot with JSP CRUD example

      In previous post, we discussed the list of Spring boot starters and also discussed the how to add starter into pom.xml. Today's post, we'll see the Spring boot with jsp CRUD operations like add, edit, delete and update.

   In the below example, I have given project name as EMS(Employee Management System, just for an example), MySQL as database to store the employee details. 

   Follow the steps as mentioned below to develop Spring boot application.

Source code is available at Github repository - Spring-boot-jsp


Database:--

First step is to set up the database, create table employee with required columns.

create database ems;

CREATE TABLE `employee` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(40) DEFAULT NOT NULL,
  `last_name` varchar(40) DEFAULT NULL,
  `user_name` varchar(20) DEFAULT NOT NULL,
  `email_id` varchar(80) DEFAULT NOT NULL,
  `emp_id` varchar(10) DEFAULT NULL,
  `blood_gp` varchar(6) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `personal_email` varchar(80) DEFAULT NULL,
  `mobile_no` varchar(16) DEFAULT NULL,
   PRIMARY KEY (`id`)
);




Project Structure:-

Create  project using Spring Initializr, as explained in previous post, How to create the Spring Boot Project using Spring Initializr tool ?

Or create project structure manually.

The following image shows the complete project structure of  spring boot application.

Spring boot with jsp Project Structure
Spring boot jsp Project Structure

Project Dependencies - Pom.xml:-

The project uses the below dependencies,

spring-boot-starter-web  -  This starter provides all dependencies and enables auto configuration

spring-boot-starter-data-jpaThis starter is used to access database for Spring and JPA.

tomcat-embed-jasper -  This Spring boot starter will enables support for JSP's(view). We need to add this dependency in pom.xml.

pom.xml,

<?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.0.RELEASE</version>  
     </parent>

    <groupId>com.ems.main</groupId>
    <artifactId>EMSApp</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
 </dependency>
        <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
 </dependency>
        <!-- JSP -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!-- jstl for jsp -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


Application Main Class - EMSApplication.java

        In the Spring boot application, EMSApplication.java is the main class to initialize the spring boot application. 

EMSApplication.java,

package com.ems.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@SpringBootApplication
public class EMSApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(EMSApplication.class, args);
    }
    
    @Bean
    public ViewResolver viewResolver() {
         final InternalResourceViewResolver r = new InternalResourceViewResolver();
         r.setPrefix("/WEB-INF/jsp/");
         r.setSuffix(".jsp");
         return r;
    }
}


Spring Controller - RegistrationController.java

The code of RegistrationController as follows,

package com.ems.main.controller;

import java.util.List;
import java.util.Map;

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 org.springframework.web.bind.annotation.RequestParam;

import com.ems.main.dto.EmployeeDTO;
import com.ems.main.service.EmployeeService;

@Controller
public class RegistrationController {

      @Autowired
      private EmployeeService employeeService;
 
      @GetMapping("/registration")
      public String reg(Map<String, Object> model) {
            model.put("employee", new EmployeeDTO());
            return "Registration";
      }
 
      @PostMapping("/home")
      public String createEmployee(@ModelAttribute("employee") EmployeeDTO empDto) {
            employeeService.createOrUpdateEmployee(empDto);
            return "redirect:/list"; 
      }
 
      @GetMapping("/list")
      public String listOfEmployee(Model model) {
            List<EmployeeDTO> employeeList = employeeService.getAllEmployee();
            model.addAttribute("empList", employeeList);
            return "employeeList";
      }
 
      @PostMapping("/delete")
      public String deleteEmployee(@RequestParam("id") String id) {
            employeeService.deleteEmployee(Long.parseLong(id));
            return "redirect:/list";  
      }
 
      @GetMapping("/edit")
      public String editEmployee(@RequestParam("id") String id, Map<String, Object> model) {
            EmployeeDTO empDTO = employeeService.editEmployee(Long.parseLong(id));
            model.put("employee", empDTO);
            return "Registration";
      }
 
}

EmployeeService.java,

This is service interface class to define the service abstract methods.

package com.ems.main.service;

import java.util.List;
import com.ems.main.dto.EmployeeDTO;

public interface EmployeeService {

       public void createOrUpdateEmployee(EmployeeDTO empDTO);
 
       public List<EmployeeDTO> getAllEmployee();
 
       public void deleteEmployee(Long id);
 
       public EmployeeDTO editEmployee(Long id);
 
}


EmployeeServiceImpl.java,

This is the service implementation class, to implement service methods.

package com.ems.main.serviceImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

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

import com.ems.main.dto.EmployeeDTO;
import com.ems.main.model.Employee;
import com.ems.main.repository.EmployeeRepository;
import com.ems.main.service.EmployeeService;

@Service
public class EmployeeServiceImpl implements EmployeeService{
 
      @Autowired
      private EmployeeRepository employeeRepository;

      public void createOrUpdateEmployee(EmployeeDTO empDto) {
            Employee emp = convertDtoToModel(empDto);
            employeeRepository.save(emp);
      }
 
      public List<EmployeeDTO> getAllEmployee() {
            List<Employee> list = employeeRepository.findAll();
            List<EmployeeDTO> employeeList = list.stream()
                .map(EmployeeDTO::new)
                .collect(Collectors.toCollection(ArrayList::new));
            return employeeList;
      }
 
      public void deleteEmployee(Long id) {
            employeeRepository.deleteById(id);
      }
 
      public EmployeeDTO editEmployee(Long id) {
            Employee emp = employeeRepository.getOne(id);
            return convertModelToDTO(emp);
      }
 
      private Employee convertDtoToModel(EmployeeDTO empDto) {
            Employee emp = new Employee();
            if (empDto.getId() != null) {
                 emp.setId(empDto.getId());
            }
            emp.setAge(empDto.getAge());
            emp.setBloodGp(empDto.getBloodGp());
            emp.setEmailId(empDto.getEmailId());
            emp.setEmpId(empDto.getEmpId());
            emp.setFirstName(empDto.getFirstName());
            emp.setLastName(empDto.getLastName());
            emp.setMobileNo(empDto.getMobileNo());
            emp.setPersonalEmail(empDto.getPersonalEmail());
            emp.setUserName(empDto.getUserName());
            return emp;
      }
 
      private EmployeeDTO convertModelToDTO(Employee emp) {
            EmployeeDTO empDTO = new EmployeeDTO();
            empDTO.setId(emp.getId());
            empDTO.setAge(emp.getAge());
            empDTO.setBloodGp(emp.getBloodGp());
            empDTO.setEmailId(emp.getEmailId());
            empDTO.setEmpId(emp.getEmpId());
            empDTO.setFirstName(emp.getFirstName());
            empDTO.setLastName(emp.getLastName());
            empDTO.setMobileNo(emp.getMobileNo());
            empDTO.setPersonalEmail(emp.getPersonalEmail());
            empDTO.setUserName(emp.getUserName());
            return empDTO;
      }
}

EmployeeRepository.java,

The EmployeeRepository class extends the JPARepository whrere you can directly use the JPA methods, like save, getone and findAll.

package com.ems.main.repository;

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

import com.ems.main.model.Employee;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{

}


Model & DTO classes:--

Employee.java,
package com.ems.main.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class Employee {
 
       @Id
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       private Long id;
 
       @Column(name="first_name")
       private String firstName;
 
       @Column(name="last_name")
       private String lastName;
 
       @Column(name="user_name")
       private String userName;
 
       @Column(name="email_id")
       private String emailId;
 
       @Column(name="emp_id")
       private String empId;
 
       @Column(name="blood_gp")
       private String bloodGp;
 
       @Column(name="age")
       private int age;
 
       @Column(name="personal_email")
       private String personalEmail;
 
       @Column(name="mobile_no")
       private String mobileNo;

       public Long getId() {
            return id;
       }

       // setters and getters for all properties
        .......
        .....
      //
}

EmployeeDTO.java,

package com.ems.main.dto;

import com.ems.main.model.Employee;

public class EmployeeDTO {
 
      private Long id;
      private String firstName;
      private String lastName;
      private String userName;
      private String emailId;
      private String empId;
      private String bloodGp;
      private int age;
      private String personalEmail;
      private String mobileNo;
 
      public EmployeeDTO() {  
      }
 
      public EmployeeDTO(Employee employee) {
          this.firstName = employee.getFirstName();
          this.lastName = employee.getLastName();
          this.userName = employee.getUserName();
          this.emailId = employee.getEmailId();
          this.empId = employee.getEmpId();
          this.bloodGp = employee.getBloodGp();
          this.age = employee.getAge();
          this.personalEmail = employee.getPersonalEmail();
          this.mobileNo = employee.getMobileNo();
          this.id = employee.getId();
      }
 
      public String getFirstName() {
          return firstName;
      }

      public void setFirstName(String firstName) {
          this.firstName = firstName;
      }
      //....
      //  ...setters and getters for all fields
      //.......
     // 
}



View Layer (JSP's)- 

employeeList.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="stag" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>EMS - Employee List</title>
<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 60%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}
</style>
</head>
<body style="background-color: #FFFFE0;">

<div style="margin-top:50px; margin-left:200px; height:50px;"><h2>Employee List</h2></div>
   <table style="margin-top: 0px;margin-left: 100px; ">
       <tr>
           <th>First Name</th>
           <th>Last Name</th>
           <th>User Name</th>
           <th>Email Id</th>
           <th>Blood Group</th>
           <th>Age</th>
           <th>Mobile No.</th>
           <th>Emp Id</th>
           <th></th>
           <th></th>
       </tr>
       <c:forEach items="${empList}" var="emp">
       <tr>
           <td>${emp.firstName}</td>
           <td>${emp.lastName}</td>
           <td>${emp.userName}</td>
           <td>${emp.emailId}</td>
           <td>${emp.bloodGp}</td>
           <td>${emp.age}</td>
           <td>${emp.mobileNo}</td>
           <td>${emp.empId}</td>
    
           <td>
              <a href="/edit?id=${emp.id}" >Edit</a>
           </td>
           <td>
              <form action="/delete?id=${emp.id}" method="post">
                <input type="submit" value="Delete" style="background:none;border:0px;cursor: pointer;"/>
              </form>
           </td>
       </tr>
       </c:forEach>
 </table>
</body>
</html>

Registration.jsp,


<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta charset="ISO-8859-1">
<title>EMS - Employee Registration</title>
<style>
td, th {
  font-family: arial, sans-serif;
}
</style>
<script type="text/javascript">
    function validate() {
         if (document.forms["employee"]["fname"].value == "") {
              alert("Please enter first name");
              document.forms["employee"]["fname"].focus();
              return false;
         }
         if (document.forms["employee"]["lname"].value == "") {
              alert("Please enter last name");
              document.forms["employee"]["lname"].focus();
              return false;
         }
         if (document.forms["employee"]["userName"].value == "") {
              alert("Please enter user name");
              document.forms["employee"]["userName"].focus();
              return false;
         }
         if (document.forms["employee"]["emailId"].value == "") {
              alert("Please enter email id");
              document.forms["employee"]["emailId"].focus();
              return false;
         }
         if (document.forms["employee"]["empId"].value == "") {
              alert("Please enter emp Id");
              document.forms["employee"]["empId"].focus();
              return false;
         }
         if (document.forms["employee"]["bloodGp"].value == "") {
              alert("Please enter blood group");
              document.forms["employee"]["bloodGp"].focus();
              return false;
         }
         if (document.forms["employee"]["age"].value == "" || document.forms["employee"]["age"].value == 0) {
              alert("Please enter valid age");
              document.forms["employee"]["age"].focus();
              return false;
         }
   }
</script>
</head>
<body style="background-color: #FFFFE0;">
<div style="margin-top:50px; margin-left:250px; height:50px;"><h2>Employee <c:out value="${employee.id != null ? 'Update' : 'Registration' }" /></h2></div>
  <form:form method="POST" modelAttribute="employee" action="/home" name="employee">
     <table style="vertical-align: center; margin-left:20%;">
 
        <tr>
            <td><form:hidden path="id"/></td>
        </tr>
        <tr>
            <td>First Name :</td>
            <td><form:input path="firstName" id="fname" /></td>
        </tr>
        <tr>
            <td>Last Name :</td>
            <td><form:input path="lastName" id="lname"/></td>
        </tr>
        <tr>
            <td>User Name :</td>
            <td><form:input path="userName" id="userName"/></td>
        </tr>
        <tr>
            <td>Email Id :</td>
            <td><form:input path="emailId" id="emailId"/></td>
        </tr>
        <tr>
            <td>Emp. Id :</td>
            <td><form:input path="empId" id="empId"/></td>
        </tr>
        <tr>
            <td>Blood Group :</td>
            <td><form:input path="bloodGp" id="bloodGp" /></td>
        </tr>
        <tr>
            <td>Age :</td>
            <td><form:input path="age" id="age" /></td>
        </tr>
        <tr>
             <td>Personal Email :</td>
             <td><form:input path="personalEmail" /></td>
        </tr>
        <tr>
             <td>Mobile No :</td>
             <td><form:input path="mobileNo" /></td>
        </tr>
        <tr>
             <td colspan="2"><input type="submit" value="<c:out value="${employee.id != null ? 'Update' : 'Register' }" />"
             onclick="return validate();">&nbsp;&nbsp; <a href="/list">Employee List</a>&nbsp;
            <c:if test="${employee.id ne null}"><b>|</b>&nbsp;<a href="/registration">Registration</a></c:if>
         </td>
    </tr>
</table>
</form:form>

</body>
</html>


application.properties
#JSP
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
spring.datasource.url=jdbc:mysql://localhost:3306/ems
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=20
spring.datasource.tomcat.min-idle=15
spring.jpa.properties.hibernate.dialect =org.hibernate.dialect.MySQLDialect


Build and Run with Maven:--

Use the below mvn command to build the application from project root directory,

mvn clean install -Dmaven.test.skip=true;

Below mvn command is used to run the Spring boot application,

mvn spring-boot:run

Now hit the URL, http://localhost:8081/list
Display the employee list as follows,




Next, Registration screen :--http://localhost:8081/registration




Edit employee, select any employee from list and click on edit,




Download or clone source code from github repository - Spring-boot-jsp

Thanks for visiting blog....


Related Posts:-
1) Spring Boot Starters
2) How to create the Spring Boot Project using Spring Initializr tool ?
3) The @SpringBootApplication Annotation usage and example
4) Spring boot advantage
5) Causes and Solution of NoSuchBeanDefinitionException in Spring.
6) Cause and solution of LazyInitializationException in Hibernate