Showing posts with label Spring interview questions and answers. Show all posts
Showing posts with label Spring interview questions and answers. Show all posts

Tuesday, 24 October 2023

How to Return DTOs from Native Queries in Spring Data JPA

         In this post, we will discuss how to return DTOs from a JPA repository method using the results of a native query without relying on entity mapping.

     JPA provides many built-in repository methods, such as findAll(), findById(), and others, for performing database operations. These methods map the query results to the corresponding entity classes.

However, in some scenarios, we need to use native SQL queries to join multiple tables and retrieve only the required data. In such cases, there may not be a suitable entity that matches the query result, making direct entity mapping impractical. Instead, we can map the native query result directly to a DTO.

This can be achieved using an interface-based DTO projection. With this approach, the JPA repository maps the native query result directly to a DTO projection, eliminating the need to first map the result to an entity and then manually convert the entity into a DTO.

Let's understand this with the following example.

JPA repository with a native query:


@Repository
public interface PropertyTaxRepository extends JpaRepository<PropertyTax, Long> {
	
     @Query(value=" SELECT z.zone as zoneName, pt.status as propertyType, SUM(pt.tax) as amountCollected "
		+ " FROM property_tax pt "
		+ " INNER JOIN zone z ON z.id=pt.zonal_classification "
		+ " group by z.zone, pt.status;", nativeQuery = true)
     public List<ReportDto> getTaxCollectedReport();
}

Create a ReportDto interface with getter methods corresponding to the fields returned by the native query. In this example, the native query selects three fields: zoneName, propertyType, and amountCollected.

The interface-based DTO is shown below:


public interface ReportDto {
      String getZoneName();
      String getPropertyType();
      BigDecimal getAmountCollected();
}

     If you have any questions or clarifications, please add comment in the comment section or send an email to anilnivargi49@gmail.com.

Thank you for visiting the blog.

Sunday, 1 October 2023

Difference Between @Component and @Bean Annotations in Spring

          As discussed in one of our previous blog posts on Spring stereotype annotations, @Component is a stereotype annotation in the Spring Framework. It is used to mark a Java class as a Spring-managed bean. During application startup, Spring scans the packages configured for component scanning, detects classes annotated with @Component, and automatically registers them as beans in the Spring container.

The @Bean annotation is used to explicitly define a bean in the Spring container. It is a method-level annotation and is typically used within a class annotated with @Configuration. The name of the @Bean method is used as the bean name by default, although it can be customized.

In summary, @Component is a class-level annotation used for automatic bean detection through component scanning, whereas @Bean is a method-level annotation used for explicit bean creation and configuration.

Difference between @Bean and @Component

Example:-

@Component
public class ProductUtil{

   //methods


}

@Bean annotation

@Configuration
class HMSAppConfiguration{

   @Bean
   public Customer getCustomer(){
      return new Customer();
   }
}


Thank you for reading the blog.

Friday, 1 September 2023

Difference Between @Resource, @Autowired, and @Inject in Spring

         In this post, we will learn the differences between the @Resource, @Autowired, and @Inject annotations. All three annotations are used for dependency injection in Spring applications. The @Resource and @Inject annotations are part of the Java specification, whereas the @Autowired annotation is provided by the Spring Framework.

@Resource – It's defined in the javax.annotation package and it's part of java.

@Inject – It's defined in the javax.inject package and it's part of Java

@Autowired – It's defined in the package org.springframework.bean.factory and part of Spring framework.

          Internally @Inject and @Autowired annotations use the AutowiredAnnotationBeanPostProcessor to inject the dependencies. But @Resource annotation internally use CommonAnnotationBeanPostProcessor to inject the dependencies. Execution path/step is same for both Inject and Autowired annotations, Resource annotation execution paths also same but order of execution paths are not same.

  • @Inject and @Autowired
         1) Matches by Type
         2) Restricts by Qualifiers
         3) Matches by Name
  • @Resource
         1) Matches by Name
         2) Matched by Type
         3) Restricts by Qualifiers

Let's discuss the execution flow of each annotation with an example.

Notification.java,
public interface Notification {
    // some methods
}

Email.java,
import org.springframework.stereotype.Component;
@Component
public class Email implements Notification {
    // some methods
}

SMS.java,
import org.springframework.stereotype.Component;
@Component
public class SMS implements Notification {
    // some methods
}

Inject the above beans into the caller java class,

@Resource
@Qualifier("invalid")
private Notification email;
 
@Autowired
@Qualifier("invalid")
private Notification email;
 
@Inject
@Qualifier("invalid")
private Notification email;

When we execute the above code, the @Resource annotation works without any errors. However, the @Autowired and @Inject annotations fail and throw an exception, as shown below.

org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [com.prj.basics.notification.Notification]

           The @Resource annotation performs dependency injection by matching the field name. In this example, it finds the bean named email and injects it successfully. However, the @Autowired and @Inject annotations resolve dependencies by type first and then use the qualifier (bean name) if one is specified. Since no bean named invalid exists, both annotations fail and throw an exception.

The following code works correctly for all three annotations without any errors.

@Resource
@Qualifier("email")
private Notification email;
 
@Autowired
@Qualifier("email")
private Notification email;
 
@Inject
@Qualifier("email")
private Notification email;

OR 

@Resource
private Email email;
 
@Autowired
private Email email;
 
@Inject
private Email email;

Thank you for visiting the blog.

Reference posts:-

Monday, 14 August 2023

How to Resolve Circular Dependency in the Spring Framework

    In this tutorial, we will discuss circular dependency in Spring. First, let's understand what a circular dependency is and how to fix it.

What is Circular Dependency in Spring ?

In Spring, a circular dependency occurs when two or more beans depend on each other.

For example, if Class A requires an instance of Class B, and Class B also requires an instance of Class A through any type of dependency injection, a circular dependency is created. In such cases, the Spring IoC container detects the circular reference at runtime and throws a BeanCurrentlyInCreationException.

In Spring Boot, circular dependencies commonly occur when using constructor injection, as shown in the following example:

import org.springframework.stereotype.Component;

@Component
public class BeanA {
    private final BeanB beanB;

    public BeanA(BeanB beanB) {
         this.beanB= beanB;
    }
}

Second bean,
import org.springframework.stereotype.Component;

@Component
public class BeanB {
    private final BeanA beanA;

    public BeanB(BeanA beanA) {
        this.beanA = beanA;
    }
}

Main Application Class,
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoSpringBootApplication{

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

}

When we run the application using IDE or command(mvn spring-boot:run) during runtime throws below error,

Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: 
Error creating bean with name 'beanA': 
Requested bean is currently in creation: Is there an unresolvable circular reference?

Solution: 

1) Use Setter injection

        As shown in the above example, the circular dependency occurs because constructor injection is used. One way to resolve this issue is to modify the classes to use setter injection instead of constructor injection.

In such cases, avoid constructor injection and use setter injection to break the circular dependency.


import org.springframework.stereotype.Component;

@Component
public class BeanA {
    private final BeanB beanB;

    @Autowired
    public void setBeanB(BeanB beanB) {
         this.beanB= beanB;
    }
}

Second Bean,
import org.springframework.stereotype.Component;

@Component
public class BeanB {
    private final BeanA beanA;
    
    @Autowired
    public void setBeanA(BeanA beanA) {
         this.beanA= beanA;
    }
}

The above approach is not recommended, you can configure circular dependencies with setter injection as well.

2)  Use Lazy Initialization

Another way to resolve a circular dependency is to annotate one of the dependent beans with @Lazy. A bean marked with @Lazy is initialized only when it is first requested, rather than during application startup. This helps break the circular dependency by delaying the creation of one of the beans.

In the previous example, you can apply the @Lazy annotation to the BeanB dependency in the setter method of the BeanA class.


import org.springframework.stereotype.Component;

@Component
public class BeanA {
    private final BeanB beanB;

    @Autowired
    @Lazy
    public void setBeanB(BeanB beanB) {
         this.beanB= beanB;
    }
}


Thank you for visiting the blog.


Reference Post:-

Saturday, 16 October 2021

Spring Stereotype Annotations

    In this post, we can learn what are the Stereotype annotations in Spring and also difference between @Component and @Bean annotations.

In Previous one of the post we discussed all Spring Annotations,  so stereotype annotations also covered but we need to see which are those Spring annotations are stereotype annotations.

     The Stereotype annotations are special type of annotations and are used to create Spring beans automatically in the application context. The Stereotype annotations are @Component, @Controller, @Service and @Repository. @Component annotation is a parent or we can say generic stereotype. The other three annotations are derived from Component annotation.

  • @Component :- Used at class level that makes the class a component.
               @Component("employee")
       class Employee{
           private String name;
           // other fields 
       }

  • @Controller:-  Used to create Spring beans at the controller layer.
                @Controller
        @RequestMapping("employee")
        public class EmployeeController {

        }
  • @Service:-  Used to create Spring beans at the Service layer.
                 @Service
        public class EmployeeService{

        }
  • @Repository:-  Used to create Spring beans for the repositories at the DAO layer.
                @Repository
        public class EmployeeRepository{

        }

Stereotype Annotations


Difference between Component and Bean annotation:-

Tuesday, 26 February 2019

Spring Boot JSP CRUD Example

      In the previous post, we discussed the different Spring Boot starters and how to add them to the pom.xml file. In today's post, we'll build a Spring Boot application with JSP that performs CRUD (Create, Read, Update, and Delete) operations.

In the following example, we'll create a simple Employee Management System (EMS). We'll use MySQL as the database to store employee information and JSP as the view technology.

Follow the steps below to develop the Spring Boot CRUD 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-jpa - This 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