Monday, 13 May 2019

Java 8 - BiConsumer, BiFunction and BiPredicate Interface Example

        We discussed in earlier posts, Java 8 Consumer Interface, method reference and forEach() method with examples. In this page or post, we will discuss about BiConsumer, BiFunction and BiPredicate Interface with examples.

       All these Interfaces accept two input parameters and returns a result. We will discuss more details of each interface as below.

  • BiConsumer (java.util.function package)

        BiConsumer is a functional interface, has one abstract method i.e accept(), similar to a Consumer Interface. The difference between consumer and BiConsumer is Consumer interface accepts single parameter where as BiConsumer accepts two input parameters, and both doesn’t return anything.

Example:-

package com.test;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

public class BiConsumerExample {
 
         public static void main(String[] args) {
      
                   //Consumer example
                  Consumer<String> strConsumer = str -> System.out.println(str);
                  strConsumer.accept("Java Wolrd");
  
                  //BiConsumer example
                  Map<String, String> map = new HashMap<String, String>();
                  map.put("Hello", "World");
                  BiConsumer<String, String> consumer = (key, value) -> System.out.println("Key - "+ key+", Value - "+value);
    
                  map.forEach(consumer);
         }

}

Output:-
Java World
Key - Hello, Value - World


  • BiFunction (java.util.function package)
         BiFunction interface is also similar to Function interface(It is also functional interface), difference is Function interface will accept one parameter but BiFunction interface accepts two parameters as a input and returns results.

Declaration:-

Interface BiFunction<T,U,R>

Here, 

T - the type of the first argument as input
U - the type of the second argument as input
R - the type of the result of the function

Example:-

package com.test;

import java.util.function.BiFunction;
import java.util.function.Function;

public class BiFunctionExample {
 
         public static void main(String[] args) {
  
                 //Function example
                Function<Integer, Integer> printNumber = a -> a*10;
                System.out.println("Number is "+printNumber.apply(10));
  
                 //BiFunction example
                BiFunction<Integer, Integer, Integer> add = (a, b) -> a+b;
                System.out.println("Summation of two number is "+add.apply(3,2));
        }

}

Output:-
Number is 100
Summation of two number is 5


  • BiPredicate (java.util.function package)

        This interface also similar to Predicate interface and it's also functional interface. Predicate interface takes one agrument as input and return boolean value. But BiPredicate interface takes two arguments as input and returns boolean data type same as Predicate interface.

Example:-

package com.test;

import java.util.function.BiPredicate;
import java.util.function.Predicate;

public class BiPredicateExample {
 
         public static void main(String[] args) {
                
                 //Predicate example
                Predicate<String> pr = a -> a.contains("A");
                System.out.println(pr.test("Anil"));
  
                 //BiPredicate example
                BiPredicate<Integer, Integer> biPrdt = (a,b) -> a>10 && b<5;
                System.out.println(biPrdt.test(11, 2));
         }
}

Output:-
true
true


Related Posts:-
1) Java 8 forEach method with examples
2) Method References in Java 8
3) Java 8 features with examples
4) Java 8 - Consumer Interface with examples

Wednesday, 8 May 2019

Method References in Java 8

       In previous post, we learned Consumer Interface in Java 8 with examples. In this post, we will discuss another new feature of java 8, i.e method references.

      A method reference is the shorthand notation for a lambda expression to call a method. In previous versions of Java, we will use object dot method name to call method of the given object. In java 8, using :: operator after the object, to call the method.

Below is the general syntax of a method reference:

Object :: methodName

The example of Method Reference uses,

Using lambda expression,

s -> System.out.println(s)

It replaces using method reference as below,

System.out::println

Examples:-

1)  Instance method of object example(Object::instanceMethod)

MethodRefExample.java,

package com.test;

interface MethodRefInterface {  
       void abstractMethod();  
} 
 
public class MethodRefExample {
  
           public void method(){  
                   System.out.println("This is a method reference example");  
           }  

           public static void main(String[] args) {
                    MethodRefExample methodRef = new MethodRefExample();  
                    MethodRefInterface ref= methodRef::method;
                    ref.abstractMethod();
           }  
}  

Output:- 

This is a method reference example


2) Static method of a Class(ClassName::methodName)

MethodRefStatic.java,

package com.test;

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

public class MethodRefStatic {
 
         public static void main(String[] args) {
                   List<Integer> list = Arrays.asList(1, 2, 3, 4);
                   System.out.println("Using lambda expression");
                   list.forEach(num -> printNumbers(num));  //using lambda expression
                   System.out.println("Using method references");
                   list.forEach(MethodRefStatic::printNumbers); //using method references
         }
 
         public static void printNumbers(int number) {
                   System.out.println("Number - " + number);
         }
}

Output:-
Using lambda expression
Number - 1
Number - 2
Number - 3
Number - 4
Using method references
Number - 1
Number - 2
Number - 3
Number - 4


3) Example of method reference to a Constructor(Class::new)

MethodRefConstruct.java,

package com.test;

interface MessageInterface{  
         MethodRefEx getMessage(String msg);  
} 

class MethodRefEx {
 
         MethodRefEx(String msg){  
                  System.out.print(msg);  
         }  
}  
class MethodRefConstruct {  
     
         public static void main(String[] args) {  
                   MessageInterface msg = MethodRefEx::new;  
                   msg.getMessage("Hello World");  
         }  
}  

Output:-
Hello World


Related Posts:--
1) Java 8 - Consumer Interface with examples
2) Java 8 forEach method with examples
3) Java 8 features with examples

Monday, 6 May 2019

Java 8 - Consumer Interface with examples

        In the current post, I will explain you the in-built functional interface Consumer introduced in Java 8 with examples. It contains two methods accept() & andThen(), comes under java.util.function package.

What is java.util.function.Consumer ?

       Consumer<T> is an in-built functional interface introduced in Java 8 and it is in the java.util.function package.  Here T is any type of input arguments. Consumer can be used in all contexts where an object needs to be consumed, i.e it will take argument as an input and some operation needs to be performed on the object without returning any result.  

       This is a functional interface because it contains only one abstract method i.e accept().

Methods in Consumer Interface

  • accept()
  • andThen()

       The accept() method is abstract method, need to implement in the code, it will take one parameter as argument and doesn't return anything.

syntax:-

    void accept(T t);

The following example shows how to use the accept() method of the Consumer interface.

package com.test;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class ConsumerInterface {
 
       public static void main(String[] args) {
  
               List<Integer> values = Arrays.asList(2,3,5,8);
               Consumer<Integer> printInt = new Consumer<Integer>() {
                        @Override
                        public void accept(Integer var) {
                                  System.out.println("Number - "+var);
                        }  
               };
  
               //print the single integer number using consumer interface.
               printInt.accept(10);
  
               //print the integers using consumer interface
               values.forEach(printInt);
       }

}

Output:--
Number - 10
Number - 2
Number - 3
Number - 5
Number - 8


andThen() -   is a default method in Consumer interface. Method andThen(), when applied on a Consumer interface, takes as input another instance of Consumer interface and returns as a result a new consumer interface which represents aggregation of both of the operations defined in the two Consumer interfaces.

syntax:-

default Consumer <T> 
        andThen(Consumer<? super T> after)

The return type of the above method is Consumer and this accepts a parameter after which is the Consumer to be applied after the current one.

The below code is to illustrate the andThen() method,

package com.test;

import java.util.function.Consumer;

public class ConsumerInterface {
 
      public static void main(String[] args) {
  
              Consumer<String> cons1 = str -> {
                        System.out.println(str + " World");
              };
      
              Consumer<String> cons2 = str -> {
                        System.out.println(str + " Java");
              };
  
              cons1.andThen(cons2).accept("Hello");
      }

}

Output:-

Hello World
Hello Java



Related Posts:-
1) Java 8 forEach method with examples
2) Java 8 features with examples

Tuesday, 9 April 2019

Java 8 forEach method with examples

        In this post, we will discuss or learn how to iterate the Map, List and Stream in java 8 using forEach method. I have given some sample examples of each collection.


  • Java 8 forEach method to iterate List

The below example is to iterate the list using foreach method and lambda expression in java 8.

package com.test;

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

public class Java8forEach {
     public static void main(String[] args) {
  
             List<String> list = new ArrayList<String>(Arrays.asList("A", "B", "C"));
  
             //Java 7, to iterate the above list
             for (String str : list) {
                   System.out.println(str);
             }
  
             //java 8, foreach method to iterate list
             list.forEach(str -> {System.out.println(str);});
     }

}

If you see the above example, you can reduce the code in Java 8 compared to earlier versions of Java.


  • Java 8 forEach method to iterate Map
In Java 8, you can iterate the map using Map.forEach(action) method and lambda expression. 

package com.test;

import java.util.HashMap;
import java.util.Map;

public class JavaforEachMap {
 
      public static void main(String[] args) {
  
           Map<Integer, String> map = new HashMap<Integer, String>();
           map.put(1, "Dell");
           map.put(2, "HCL");
           map.put(3, "Toshiba");
  
           //Java 7(earlier versions), iterate a Map
           for (Map.Entry<Integer, String> entry : map.entrySet()) {
                System.out.println("Key - "+entry.getKey() +" Value - "+entry.getValue());
           }
  
           //Java 8, iterate Map using forEach() method and lambda expression
           map.forEach((k,v) -> {
                System.out.println("key - "+k + " Value - "+v);
           });
     }

}


  • Iterate a List using Stream API and forEach() method

        In java 8, java.util.Stream represents a stream on which one or more operations can be performed. Stream operations are either intermediate or terminal. Stream terminal operations return a result of a certain type, intermediate operations return the stream itself so you can chain multiple method calls in a row. Streams are created on a source, e.g. a java.util.Collection like lists or sets (maps are not supported). Stream operations can either be executed sequential or parallel.

      Compare java 7 and earlier versions and java 8 code to iterate a list with certain conditions as follows,

package com.test;

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

public class Java8Stream {
 
      public static void main(String[] args) {
  
            List<String> list = new ArrayList<String>(Arrays.asList("abc", "bcd", "afd", "art"));

            //Java 7, to iterate list with some conditions
            for (String str : list) {
                 if (str.contains("a")) {
                       System.out.println(str);
                 }
            }
  
           //same example in java 8 using foreach() and stream api
           list.stream().filter(a -> a.contains("a")).forEach(str -> {
                 System.out.println(str);
           });
      }

}


Friday, 8 March 2019

Permission denied(publickey), fatal:couldn't read from remote repository - Gihub Error

     In the current post, we will check one of the gihub error while accessing the private repository code. I faced this issue recently when I try to access(git clone) private repository without adding ssh key into git-hub account.

The error message is,

C://WS/repo> git clone "URL Of PrivateRepo"

Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

This means that GitHub is not able to authenticate you. There are two reasons,

1) You might not set up with a SSH key .  OR
2) Your generated SSH key is not associated with GitHub account.

First, we need to create SSH key to access the private Repository.

Create new SSH Key:-

 Open terminal of any directory, and type below command.  

$ ssh-keygen -t rsa -b 4096 -C "type your email here"

After enter the above command, then need to enter file name  to save the ssh key, by default it should save in the home directory of ssh folder.

Generating public/private rsa key pair.
Enter file in which to save the key (/home/administrator/.ssh/id_rsa):

Then enter the passphrase, or leave as it is just enter,

Enter passphrase (empty for no passphrase): [Type a passphrase]

After running all above commands, the SSH key will generate and it will save mentioned directory.

dir/id_rsa  , dir/id_rsa.pub

Copy the contents from id_rsa.pub file, and key should start with ssh-rsa,
and you can add into github account.


Add generated SSH key to GitHub account:--

Login to your GitHub account using basic credentials, i.e username/email and password.

Then go to Setting -> SSH and GPG keys 

SSH key generation


Click on New SSH Key,

Add SSH Key into Github account

Give key title, then add the generated key in the text box, key should start with ssh-rsa or ssh-dss or above mentioned text.
click on Add SSH key. It will add into the GitHub account.

Enable the key as follows,

Enable SSH Key

If you follow above steps properly, then you can able to access the code of private Repository.

Any doubt or clarifications, please put comment in the comment section.

Thank you......

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