0% found this document useful (0 votes)
26 views

Jpa MVC

Uploaded by

subhabirajdar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Jpa MVC

Uploaded by

subhabirajdar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

ADVANCE JAVA

JPA (Java Persistence API) is also called as “Jakarta Persistence API”, The Java Persistence
API (JPA) is a specification of Java. It is used to persist data between Java object and relational
database. JPA acts as a bridge between object-oriented domain models and relational database
systems.
As JPA is just a specification, we don‟t write any SQL Query here, ORM (Object Relational
Mapping) tools like Hibernate, TopLink and iBatis does itself.
Example: Let‟s create a table in database with name “Student”.

Table Name : Student


Id Name Course Fee

Create a class with same name as table in DB, & create variable equal to the no. of columns in
that table & make getters & setters for that variables. This class is called as “Entity Class”.
Now create the object of the entity class and put all the data in that object like id, name, course
and fee, now JPA takes the data of the object and puts it into the table in database & the ORM
which implements this in is called Hibernate (We‟re using Hibernate).

Q . What is Hibernate?
A. Hibernate is an ORM (Object Relational Mapping) tool. JPA defines the concept of ORM, but
implementation of that is done in Hibernate, Eclipse Link etc..

As a beginner when working on Spring Boot Projects, follow the below steps:
1. Create Database Schema (Tables)
2. Create Entity Class
3. Configure “application.properties” file (with DB details)
4. Create Repository Layer (Interface)
5. Perform JUnit Testing
The first 3 steps belongs to Hibernate (anything imported from “javax.persistence” package
belongs to Hibernate), 4th Step belong to Spring Boot (Repository layer has lot of built-in
methods using which we can perform CRUD Operations with DB).

Key points to remember in Spring Boot:


 Object is called as “bean” in Spring Boot
 @Autowired annotation is used for creating beans (Objects) in Spring Boot, it‟s called as
“DI” (Dependency injection), injecting the object address into reference variable.

1
ADVANCE JAVA
Example: Let‟s create a project named “demo_crud” to perform CRUD Operations on Student‟s
data.
Step #1: Create Database Schema (Tables)
create database demo_crud
use demo_crud
create table student
(
ID int primary key auto_increment,
Name varchar (45),
Course varchar (45),
Fee int
)

select * from student


Here primary key means ID should be unique and auto_increment declares value should be
increased automatically.

Step #2: Create Entity Class


package com.demo_crud.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity //This annotation describes that this is a Special class whose object data will
be stored in DB table, Entity=Table in DB
public class Student {
//variable name should match with the column names in DB
@Id //It declares that this is a Primary Key
@GeneratedValue(strategy = GenerationType.IDENTITY) //It declares that the Id has
auto increment in its values
private long id; //Using Long" instead of "int" here because, Long can store more
data than int
private String name;
private String course;
private int fee;

public long getId() {


return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCourse() {
return course;
}

2
ADVANCE JAVA

public void setCourse(String course) {


this.course = course;
}
public int getFee() {
return fee;
}
public void setFee(int fee) {
this.fee = fee;
}
}

Step #3: Configure “application.properties” file (with DB details)


spring.datasource.url=jdbc:mysql://localhost:3306/demo_crud
spring.datasource.username=root
spring.datasource.password=Test

Step #4: Create Repository Layer (Interface)


package com.demo_crud.repository;
import org.springframework.data.repository.CrudRepository;
import com.demo_crud.entities.Student;

public interface StudentRepository extends CrudRepository<Student, Long> {


//Perform CRUD Operations on "Student" Class and Primary key wrapper class name, it
wont take "long" so apply wrapper class and put "Long"
}

Step #4: Perform JUnit Testing


package com.demo_crud;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.demo_crud.entities.Student;
import com.demo_crud.repository.StudentRepository;

@SpringBootTest
class DemoCrudApplicationTests {

@Autowired //Dependency Injection


private StudentRepository studentRepo; //Ref. variable of Interface

@Test
void saveOneStudent() {
Student s1 = new Student();
s1.setName("Mike");
s1.setCourse("Development");
s1.setFee(1000);

studentRepo.save(s1);
}
}

3
ADVANCE JAVA
Now we have successfully saved the data of one student in MySQL DB without writing Query.

Let‟s save one more student‟s data.


package com.demo_crud;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.demo_crud.entities.Student;
import com.demo_crud.repository.StudentRepository;

@SpringBootTest
class DemoCrudApplicationTests {

@Autowired //Dependency Injection


private StudentRepository studentRepo; //Ref. variable of Interface

@Test
void saveOneStudent() {
Student s1 = new Student();
s1.setName("Stallin");
s1.setCourse("Testing");
s1.setFee(800);

studentRepo.save(s1);
}
}

We can also delete the data of any student using ID#, but the deleted ID# will not be assigned
to the next record, once deleted, permanently deleted, because we‟re using primary key for
IDs, so every entry has unique ID#, so the next save method will insert ID#3 after deleting
Stallin‟s record which is assigned ID#2.

4
ADVANCE JAVA
package com.demo_crud;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.demo_crud.entities.Student;
import com.demo_crud.repository.StudentRepository;

@SpringBootTest
class DemoCrudApplicationTests {

@Autowired //Dependency Injection


private StudentRepository studentRepo; //Ref. variable of Interface

@Test
void saveOneStudent() {
Student s1 = new Student();
s1.setName("Stallin");
s1.setCourse("Testing");
s1.setFee(800);

studentRepo.save(s1);
}

@Test
void deleteOneStudent() {
studentRepo.deleteById(2L); //Deleting ID#2 (Stallin's Record)
//Just select delete method name and run, if we run directly the above save
method will also run and again same data will be saved with next ID number
}
}

5
ADVANCE JAVA

Before going forward in Student Project‟s CRUD Operations, let‟s learn about Optional Class.

OPTIONAL CLASS
Java 8 introduced a new public final class “Optional” in java.util package. It is used to
deal with NullPointerException in java application. It provides the methods to easily check
whether a variable has null value or not, this is an alternative way of handling
NullPointerException other than Try Catch Block, the commonly used methods of Java Optional
class are:
Optional.ofNullable(): It returns a Non-empty Optional if the given object has a value,
otherwiseit returns an empty Optional.
isPresent(): It is used check whether the particular Optional object is empty or no-empty.
ifPresent(): It only executes if the given Optional object is non-empty.
Example: (with NullPointerException)
package p1;
public class A {
int x =10;
static A a1; //a1 is null reference variable
public static void main(String[] args) {
System.out.println(a1.x);
}
}

Output:
Exception in thread "main" java.lang.NullPointerException
at p1.A.main(A.java:6)

(with Optional Class)


package p1;
import java.util.Optional;
public class A {
int x =10;
static A a1; //a1 is null reference variable
public static void main(String[] args) {
Optional<A> val = Optional.ofNullable(a1);
System.out.println(val);
System.out.println(val.isPresent()); //if value present true, otherwise false
}
}

Output:
Optional.empty
false

6
ADVANCE JAVA
(Applying if condition, If value is present, it prints value, otherwise else part)
package p1;
import java.util.Optional;
public class A {
int x =10;
static A a1 = new A(); //a1 is not null
public static void main(String[] args) {
Optional<A> val = Optional.ofNullable(a1);
if(val.isPresent()) {
System.out.println(a1.x);
}else {
System.out.println("No Value Present");
}
}
}

Output:
10

(here a1 is null, so else part will run)


package p1;
import java.util.Optional;
public class A {
int x =10;
static A a1; //a1 is null
public static void main(String[] args) {
Optional<A> val = Optional.ofNullable(a1);
if(val.isPresent()) {
System.out.println(a1.x);
}else {
System.out.println("No Value Present");
}
}
}

Output:
No Value Present

7
ADVANCE JAVA

JPA (JAVA PERSISTENCE API) (Contd…)


Now let‟s Read one student data by ID#1 (ID#1 is present in database)
package com.demo_crud;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.demo_crud.entities.Student;
import com.demo_crud.repository.StudentRepository;

@SpringBootTest
class DemoCrudApplicationTests {

@Autowired //Dependency Injection


private StudentRepository studentRepo; //Ref. variable of Interface

@Test
void saveOneStudent() {
Student s1 = new Student();
s1.setName("Sameer");
s1.setCourse("Development");
s1.setFee(5000);
studentRepo.save(s1);
}

@Test
void deleteOneStudent() {
studentRepo.deleteById(2L); //Deleting ID#2 (Stallin's Record)
}

@Test
void getOneStudent() {
Optional<Student> findById = studentRepo.findById(1L); //ID#1 is present
if(findById.isPresent()){ //it will put the return data in optional object
Student student = findById.get();
//"get" will convert it to student(entity) object
System.out.println(student.getId());
System.out.println(student.getName());
System.out.println(student.getCourse());
System.out.println(student.getFee());
}else {
System.out.println("No Record Found");
}
}
}

Output:
1
Mike
Development
1000

8
ADVANCE JAVA
Let‟s find by ID#10 (ID#10 is not present in database
package com.demo_crud;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.demo_crud.entities.Student;
import com.demo_crud.repository.StudentRepository;

@SpringBootTest
class DemoCrudApplicationTests {

@Autowired //Dependency Injection


private StudentRepository studentRepo; //Ref. variable of Interface

@Test
void saveOneStudent() {
Student s1 = new Student();
s1.setName("Sameer");
s1.setCourse("Development");
s1.setFee(5000);
studentRepo.save(s1);
}

@Test
void deleteOneStudent() {
studentRepo.deleteById(2L); //Deleting ID#2 (Stallin's Record)
}

@Test
void getOneStudent() {
Optional<Student> findById = studentRepo.findById(10L); //ID#10 isn’t present
if(findById.isPresent()){ //it will put the return data in optional object
Student student = findById.get();
//"get" will convert it to student(entity) object
System.out.println(student.getId());
System.out.println(student.getName());
System.out.println(student.getCourse());
System.out.println(student.getFee());
}else {
System.out.println("No Record Found");
}
}
}

Output:
No Record Found

If we wouldn‟t have used Optional Class here, as there was no data with ID#10 was present in
DB, it would have resulted “NullPointerException”, because findById is null, & with null ref
variable if we call get method it is “NullPointerException”.

Now let‟s update the Record. Updating Mike‟s (ID#1) data.


Database before updating:

9
ADVANCE JAVA

Example: (Mike wants to change the Course from development to Testing)


package com.demo_crud;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.demo_crud.entities.Student;
import com.demo_crud.repository.StudentRepository;

@SpringBootTest
class DemoCrudApplicationTests {

@Autowired //Dependency Injection


private StudentRepository studentRepo; //Ref. variable of Interface

@Test
void updateOneStudent() { //Updating ID#1
Optional<Student> findById = studentRepo.findById(1L);
if(findById.isPresent()){
Student student = findById.get();
student.setCourse("Testing");
student.setFee(800);
studentRepo.save(student);
}else {
System.out.println("No Record Found");
}
}
}

Mike‟s data has been successfully updated, database:

Let‟s find All Student data.

10
ADVANCE JAVA
package com.demo_crud;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.demo_crud.entities.Student;
import com.demo_crud.repository.StudentRepository;

@SpringBootTest
class DemoCrudApplicationTests {

@Autowired //Dependency Injection


private StudentRepository studentRepo; //Ref. variable of Interface

@Test
void getAllStudent() {
Iterable<Student> findAll = studentRepo.findAll();
for (Student s : findAll) {
System.out.println(s.getId()+" "+s.getName()+" "+s.getCourse()+" "+s.getFee());
}
}
}

Output:
1
3
4

Answer:
@Test
void getAllStudent() {
Iterable<Student> findAll = studentRepo.findAll();
findAll.forEach( (s) -> { //Using Lambda Expression
System.out.println(s.getId()+" "+s.getName()+" "+s.getCourse()+" "+s.getFee()); });
}

11
ADVANCE JAVA

Here we are going to develop a project for “Marketing Lead”, (“Lead” is a marketing
terminology, A potential customer enquiring about the product is called as lead).
For this project on Spring Boot, we are following the below steps:
1. Create Database Schema (Tables) using JAVA Code
2. Create Entity Class
3. Configure “application.properties” file (with DB details)
4. Create Repository Layer (Interface)
5. Configure Jasper Tomcat
6. View Layer
7. Controller Layer
8. Service Layer

Step #1: Create Database Schema (Local instance MySQL>Create new Schema)

Step #2: Create Entity Class


package com.marketing.entities;
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(name = "leads") //Annotation should be used when table name needed in DB is dif-
ferent than class name
public class Lead {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) //primary & auto increment
private long id;

12
ADVANCE JAVA
@Column(name = "first_name", nullable=false)
//Annotation should be used when column name needed in DB is different than method
name, it shouldn't have null value
private String firstName;

@Column(name = "last_name", nullable=false)


private String lastName;

@Column(nullable=false, unique=true) //no null value & should be unique, to avoid


duplicate data in database
private String email;

@Column(nullable=false, unique=true) //nullable=false means the data is mandatory


private long mobile;

public long getId() {


return id;
}

public void setId(long id) {


this.id = id;
}

public String getFirstName() {


return firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public long getMobile() {


return mobile;
}

public void setMobile(long mobile) {


this.mobile = mobile;
}
}

13
ADVANCE JAVA
Step #3: Configure “application.properties” file (with DB details)
spring.datasource.url=jdbc:mysql://localhost:3306/marketing_lead_db
spring.datasource.username=root
spring.datasource.password=Test

#This line helps to create table in database using entity class,


#After running once on "create" don't forget to change it to "update".
#Otherwise on every server restart the table will be dropped off
spring.jpa.hibernate.ddl-auto=update

#Path of the jsp file and its extension


spring.mvc.view.prefix=/WEB-INF/jsps/
spring.mvc.view.suffix=.jsp

Step #4: Create Repository Layer (Interface)


Created the Repository Layer (interface) with extended interface “JpaRepository” instead of
“CurdRepository” because it‟s an update of CRUD & can perform more operations than
CrudRepository.

package com.marketing.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.marketing.entities.Lead;
public interface LeadRepository extends JpaRepository<Lead, Long> { //Lead is Entity Class
}

Step #5: Configure Jasper Tomcat


Dependency tag to configure Jasper Tomcat:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>

14
ADVANCE JAVA

Step #5: View Layers (Lead)


Create folders manually in src>main>webapp > WEB-INF > jsps.

JSP Page (View Layer) “create_lead.jsp”:


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ include file="Menu.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title> Create Lead </title>
</head>
<body>
<h2> Create Lead </h2>
<form action="saveLead" method="post">
<table>
<tr><td>First Name</td><td><input type="text" name="firstName"/></td></tr>
<tr><td>Last Name</td><td><input type="text" name="lastName"/></td></tr>
<tr><td>Email</td><td><input type="text" name="email"/></td></tr>
<tr><td>Mobile</td><td><input type="text" name="mobile"/></td></tr>
<tr></tr>
<tr><td style="text-align:center" colspan="2"><input type="submit" value="Save Lead"/></td></tr>
</table>

</form>
${msg}
</body>
</html>

JSP Page (View Layer) “Menu.jsp”:


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<a href="createLead"> <input type="button" value="Create Lead"> </a>
<a href="listAll"> <input type="button" value="List of All Leads"> </a>
<hr>
</body>
</html>

15
ADVANCE JAVA

After creating “create_lead.jsp” and “Menu.jsp” let‟s go ahead with Controller Layers.
Step #6: Controller Layers

Lead Controller Page (Controller Layer) “LeadController.java”:


package com.marketing.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.marketing.dto.LeadData;
import com.marketing.entities.Lead;
import com.marketing.services.LeadService;

@Controller
public class LeadController {

@Autowired //Dependency Injection


private LeadService leadService;

//handler method, To navigate to “create_lead.jsp”, because only controller can access this
@RequestMapping("/createLead") //acts like @WebServlet
public String viewCreateLeadPage() {
return "create_lead"; //acts like RequestDispatcher
//path of this jsp file given in "application.properties"
}

In this Spring Boot project also, we follow MVC Architecture.

A.

16
ADVANCE JAVA

Step #7: Services Layers

Service Layer: Interface (LeadService.java)


package com.marketing.services;
import java.util.List;
import com.marketing.entities.Lead;

public interface LeadService {


public void saveLead(Lead l);
public List<Lead> listLeads();
public void deleteLeadById(long id);
public Lead getOneLead(long id);
}

Service Layer: Class (LeadServiceImpl.java)


package com.marketing.services;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.marketing.entities.Lead;
import com.marketing.repositories.LeadRepository;

@Service
public class LeadServiceImpl implements LeadService {

@Autowired //Dependency Injection


private LeadRepository leadRepo;

@Override
public void saveLead(Lead l) {
leadRepo.save(l); //To save data in to the database
}

@Override
public List<Lead> listLeads() {
List<Lead> leads = leadRepo.findAll(); //To read data in the database
return leads;
}

@Override
public void deleteLeadById(long id) {
leadRepo.deleteById(id); //To delete data from the database
}

@Override
public Lead getOneLead(long id) {
Optional<Lead> findById = leadRepo.findById(id); //findrecord by ID# in the database
Lead lead = findById.get();
return lead;
}
}

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 17


ADVANCE JAVA
In Create Lead JSP Page, after putting all the form details, clicking on the “Save Lead” button
will call @RequestMapping("/saveLead") from “LeadController.java”.
There are multiple ways to transfer object data from “View Layer” to database.
Method #1: To Save data from View Layer to the database (LeadController.java)
//Method #1
@RequestMapping("/saveLead")
public String saveOneLead(@ModelAttribute("lead") Lead l, ModelMap model) {
//ModelAttribute("lead")-"lead" object stores the data & ref variable is "l"
//"Lead" is a entity class and "l" is ref. variable
// ModelMap is same as "Request.set & getAttribute" to put back message in View Layer
leadService.saveLead(l);
model.addAttribute("msg", "Lead Saved Successfully");
return "create_lead";

Note: Every time restarting the servers manually is painful, let‟s make it automatic so that
whenever we make any changes to our project, server should automatically restart (Live
Loading). To do that Right Click on the project, & in cascade menu select Spring>Add DevTools.

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 18


ADVANCE JAVA

Method #2: To Save data from View Layer to the database (LeadController.java)
//Method#2: it will make the method argument lengthy if working with huge no. of fields, Recom-
mended for less no. of fields
@RequestMapping("/saveLead")
public String saveOneLead(@RequestParam("name") String fName, @RequestParam("LastName")
String lName, @RequestParam("emailId") String mail, @RequestParam("mobileNumber") long mobile) {
Lead l = new Lead(); //lead Object is needed to save data in DB
l.setFirstName(fName);
l.setLastName(lName);
l.setEmail(mail);
l.setMobile(mobile);
leadService.saveLead(l);
return "create_lead";
}

JSP Page of Method #2:


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title> Create Lead 2 </title>
</head>
<body>
<h2> Registration | Create </h2>
<form action="saveLead" method="post">
<pre>
<!-- Method#2: In name attribute we're giving different names other than entity class -->
First Name <input type="text" name="name"/>
Last Name <input type="text" name="LastName"/>
Email <input type="text" name="emailId"/>
Mobile <input type="text" name="mobileNumber"/>
<input type="submit" value="Save Lead"/>
</pre>
</form>
</body>
</html>

Method #3: To Save data from View Layer to the database (LeadController.java)
//Method#3: DTO- Data Transfer Object
@RequestMapping("/saveLead")
public String saveOneLead(LeadData data, ModelMap model) {
//Press Ctr+1, Create "LeadData" class in dto package
Lead ld = new Lead(); //lead Object is needed to save data in DB
ld.setFirstName(data.getFirstName());
ld.setLastName(data.getLastName());
ld.setEmail(data.getEmail());
ld.setMobile(data.getMobile());

leadService.saveLead(ld);
model.addAttribute("msg", "Lead Saved Successfully");
return "create_lead";
}

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 19


ADVANCE JAVA
LeadData Class for Method #3 in DTO Package:
package com.marketing.dto;
public class LeadData { //This is an ordinary JAVA Class
//Create variables matching to .jsp file from attribute names
private long id;
private String firstName;
private String lastName;
private String email;
private long mobile;
//Getters and Setters
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public long getMobile() { return mobile; }
public void setMobile(long phone) { this.mobile = phone; }
}

JSP Page of Method #3:


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title> Create Lead </title>
</head>
<body>
<h2> Registration | Create </h2>
<form action="saveLead" method="post">
<pre>
First Name <input type="text" name="firstName"/>
<!-- name attribute should exactly match with variable name in DTO class -->
Last Name <input type="text" name="lastName"/>
Email <input type="text" name="email"/>
Mobile <input type="text" name="phone"/>
<input type="submit" value="Save Lead"/>
</pre>
</form>
${msg}
</body>
</html>

Database:

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 20


ADVANCE JAVA

Before going further in project let‟s first look at “JSTL”

JSTL (Jakarta Standard Tag Library)


The Jakarta Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development.
Advantage of JSTL:
 Fast Development JSTL provides many tags that simplify the JSP.
 Code Reusability We can use the JSTL tags on various pages.
 No need to use scriptlet tag, It avoids the use of scriptlet tag.
 We can write JAVA code with JSTL tags.

JSTL mainly provides five types of tags:

Tag Name Description

Core tags The JSTL core tag provide variable support, URL management, flow control,
etc. The URL for the core tag is http://java.sun.com/jsp/jstl/core. The prefix of
core tag is c.

Function The functions tags provide support for string manipulation and string length.
tags The URL for the functions tags is http://java.sun.com/jsp/jstl/functions and
prefix is fn.

Formatting The Formatting tags provide support for message formatting, number and
tags date formatting, etc. The URL for the Formatting tags
is http://java.sun.com/jsp/jstl/fmt and prefix is fmt.

XML tags The XML tags provide flow control, transformation, etc. The URL for the XML
tags is http://java.sun.com/jsp/jstl/xml and prefix is x.

SQL tags The JSTL SQL tags provide SQL support. The URL for the SQL tags
is http://java.sun.com/jsp/jstl/sql and prefix is sql.
Source

The JSTL.jar file is needed run the JSTL Tags, Click below to download JSTL_1.2.jar

After downloading paste the .jar file into scr>main>webapp>WEB-INF>lib.

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 21


ADVANCE JAVA
JSTL Core Tags:
JSTL Core Tag Description
<c:out> To write something in JSP page, we can use EL also with this tag
<c:import> Same as <jsp:include> or include directive
<c:redirect> redirect request to another resource
<c:set> To set the variable value in given scope.
<c:remove> To remove the variable from given scope
<c:catch> To catch the exception and wrap it into an object.
Simple conditional logic, used with EL and we can use it to process the
<c:if>
exception from <c:catch>
Simple conditional tag that establishes a context for mutually exclusive
<c:choose>
conditional operations, marked by <c:when> and <c:otherwise>
<c:when> Subtag of <c:choose> that includes its body if its condition evalutes to „true‟.
<c:otherwise> Subtag of <c:choose> that includes its body if its condition evalutes to „false‟.
<c:forEach> for iteration over a collection
<c:forTokens> for iteration over tokens separated by a delimiter.
<c:param> used with <c:import> to pass parameters
<c:url> to create a URL with optional query string parameters

Example #1:
<%@ 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"%> <!-- JSTL Directive Tag -->
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title> JSTL Tag </title>
</head>
<body>
<c:set var="val" value="100"></c:set>
<c:out value="${val}"></c:out>
</body>
</html>

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 22


ADVANCE JAVA
Example #2:
<%@ 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"%> <!-- JSTL Directive Tag -->
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title> JSTL Tag </title>
</head>
<body>
<c:set var="val" value="Hello"></c:set>
<c:out value="${val}"></c:out>
</body>
</html>

Example #3:
<%@ 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"%> <!-- JSTL Directive Tag -->
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title> JSTL Tag </title>
</head>
<body>
<c:forEach var="j" begin="1" end="5">
<p>${j}</p>
</c:forEach>
</body>
</html>

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 23


ADVANCE JAVA
Let‟s get back to our Web Development Project (Marketing Lead)

WEB DEVELOPMENT PROJECT (contd…)


By clicking on the “list of All Leads” button in the Menu will call @RequestMapping("/listAll")
To read all the data from the database. (LeadController.java)
@RequestMapping("/listAll")
public String listAllLeads(ModelMap model) {
List<Lead> leads = leadService.listLeads();
model.addAttribute("lds", leads);
return "leadSearchResult";

Q. Difference between CRUD Repository and JPA Repository.?


A. In JPA Repository findAll method returns “List” and CRUD Repository returns iterable.

Add the dependency tag to download & use JSTL 1.2 in Spring Boot.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version><!--$NO-MVN-MAN-VER$-->
</dependency>
After adding the dependency jar, don‟t rely on auto start, re-start server manually to configure
JSTL jar completely.
“listAll” method from “LeadController.java” will return the “leadSearchResult.jsp”.
List of all the Leads JSP Page (leadSearchResult.jsp)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ include file="Menu.jsp" %>
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"%> <!-- JSTL Directive Tag -->
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>All Leads</title>
</head>
<body>
<table border=1>
<tr><th colspan="7" bgcolor="lightgrey"><font size="6"> LIST OF LEADS </font></th></tr>
<tr bgcolor="lightgrey">
<th>Id No.</th><th>First Name</th><th>Last Name</th><th>Email</th><th>Mobile</th><th col-
span="2">Action</th>
</tr>
<c:forEach var="leads" items="${lds}">
<tr><td style="text-align:center"> ${leads.id} </td>
<td> ${leads.firstName} </td>
<td>${leads.lastName}</td>
<td>${leads.email}</td>
<td>${leads.mobile}</td>
<td><a href="delete?id=${leads.id}">
<input style="background-color:mistyrose; color:darkred" type="submit" value="Delete">
</a></td>
<td><a href="update?id=${leads.id}">
<input style="background-color:lightcyan; color:darblue" type="submit" value="Update">
</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 24


ADVANCE JAVA
WebPage of “leadSearchResult.jsp”:

Localhost:8080/listAll

DELETING A RECORD FROM DATABASE


To delete a lead by clicking on the delete button will call @RequestMapping("/delete") from
“LeadController.java”.
To delete the data from the database. (LeadController.java)
@RequestMapping("/delete")
public String deleteOneLead(@RequestParam ("id") long id, ModelMap model) {
leadService.deleteLeadById(id);

List<Lead> leads = leadService.listLeads();


model.addAttribute("lds", leads);
return "leadSearchResult"; //After delete stay on the same page
}

Let‟s delete Stallin‟s data:

UPDATING A RECORD IN THE DATABASE


To update the record, clicking on the update button will call @RequestMapping("/update")
from “LeadController.java”.
To get the particular id data in the database. (LeadController.java)
@RequestMapping("/update")
public String updateOneLead(@RequestParam ("id") long id, ModelMap model) {
Lead lead = leadService.getOneLead(id);
model.addAttribute("leadUpd", lead);
return "updateLead";
Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 25
ADVANCE JAVA
}

This will redirect to “updateLead.jsp” with that particular record.


JSP Page (updateLead.jsp)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ include file="Menu.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title> Update Lead </title>
</head>
<body>
<form action="updateLead" method="post">
<table border=1>
<tr>
<td style="text-align:center" colspan="2" bgcolor="lightgrey">
<input type="hidden" name="id" value="${leadUpd.id}"><font size="4"> UPDATE THE LEAD DE-
TAILS </font></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" name="firstName" value="${leadUpd.firstName}"/></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastName" value="${leadUpd.lastName}"/></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="${leadUpd.email}"/></td>
</tr>
<tr>
<td>Mobile</td>
<td><input type="text" name="mobile" value="${leadUpd.mobile}"/></td>
</tr>
<tr>
<td style="text-align:center" colspan="2"><input type="submit" value="Update"/></td>
</tr>
</table>
</form>
</body>
</html>

Let‟s update Mike‟s Email and Mobile Number:

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 26


ADVANCE JAVA

After clicking on update, it will call @RequestMapping("/updateLead") in


“LeadController.java”.

To update the data in the database. (LeadController.java)


@RequestMapping("/updateLead")
//Using DTO Method to update Lead data as we don't have entity class here
public String updateOneLeadData(LeadData data, ModelMap model) {
Lead ld = new Lead();
ld.setId(data.getId());
ld.setFirstName(data.getFirstName());
ld.setLastName(data.getLastName());
ld.setEmail(data.getEmail());
ld.setMobile(data.getMobile());
leadService.saveLead(ld);
List<Lead> leads = leadService.listLeads();
model.addAttribute("lds", leads);
return "leadSearchResult";
}
}

This will redirect back to the “leadSearchResult.jsp” with the updated details.

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 27


ADVANCE JAVA

It helps us to integrate heterogenous and homogenous applications.

XML Consumer/Client
J2EE

.NET PHP J2EE

XML Exposer XML Exposer XML Exposer

XML Exposer
J2EE

.NET PHP J2EE

XML Consumer/Client XML Consumer/Client XML Consumer/Client

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 28


ADVANCE JAVA
Technical Flow of Web Services Layer:

Example:
Create a class named “LeadRestController.java” in Controller layer of project “marketing”
package com.marketing.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.marketing.entities.Lead;
import com.marketing.services.LeadService;

@RestController //Web Service Layer


@RequestMapping("/api/leads")
public class LeadRestController {

@Autowired //to Interact with DB


private LeadService leadService;

@GetMapping
public List <Lead> getAllleads() {
List<Lead> leads = leadService.listLeads();
return leads;
}
}

Web Output:

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 29


ADVANCE JAVA

Web Services is nothing but developing a url to interact with the database.
There are two ways we can implement web services:
1. SOAP: Here we exchange the data between the applications using XML file,
implementation of SOAP web services is complex, because we need to parse
programmatically XML file.
2. REST: In Rest web services we exchange the data between applications using JSON
Object (JAVA Script Object Notation), Implementation of Rest services is easy. However
Rest services also supports XML files.

Now a days we‟re using JSON in place of XML.


JSON stands for JavaScript object notation. JSON has been derived from javascript, where
javascript is a programming language. It was originally created to hold the structured data that
could be used in javascript. JSON became so popular that it is used for data for all kinds of
applications. It is the most popular way of sending the data for Web APIs.

Basic data types supported by json are:


Strings: Characters that are enclosed in single or double quotation marks.
Number: A number could be integer or decimal, positive or negative.
Booleans: The Boolean value could be either true or false without any quotation marks.
Null: Here, null means nothing without any quotation marks.
In addition to basic data types, json has arrays and objects.

Q. Difference between JSON and XML.?


JSON XML

JSON stands for javascript object notation. XML stands for an extensible markup language.

The extension of json file is .json. The extension of xml file is .xml.

The internet media type is application/json. The internet media type is application/xml or text/xml.

The type of format in JSON is data interchange. The type of format in XML is a markup language.

It is extended from javascript. It is extended from SGML.


It is open source means that we do not have to It is also open source.
pay anything to use JSON.

The object created in JSON has some type. XML data does not have any type.
The data types supported by JSON are strings, XML data is in a string format.
numbers, Booleans, null, array.

It does not have any capacity to display the data. XML is a markup language, so it has the capacity to display the
content.

JSON has no tags. XML data is represented in tags, i.e., start tag and end tag.

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 30


ADVANCE JAVA
XML file is larger. If we want to represent the data in XML then it
would create a larger file as compared to JSON.

JSON is quicker to read and write. XML file takes time to read and write because the learning curve is
higher.

JSON can use arrays to represent the data. XML does not contain the concept of arrays.
It can be parsed by a standard javascript function. XML data which is used to interchange the data, must be parsed with
It has to be parsed before use. respective to their programming language to use that.

It can be easily parsed and little bit code is It is difficult to parse.


required to parse the data.

File size is smaller as compared to XML. File size is larger.

JSON is data-oriented. XML is document-oriented.


It is less secure than XML. It is more secure than JSON.

JSON Example:
{"employees":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]}

XML Example:
<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>

CRUD OPERATIONS IN WEB SERVICES


In order to test the Web Services CRUD operations, we‟re using a software named “Postman”.
Download it from here (for Windows 64-Bit).
Click here to Download

Reading the Data:


To read the data using web services we just need to enter the url of the api using “GET” method
in Postman, here in this case we are using (localhost:8080/api/leads) .
The result will be shown in the form of JASON Object.

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 31


ADVANCE JAVA
Example:

Saving the Data:


To save the data using web services we need to create a method in “LeadRestController.java”
@PostMapping //used to save data in the database
public void saveOneLead(@RequestBody Lead lead) {
//@RequestBody to read the data from the JSON Object & put it into Lead's Object

leadService.saveLead(lead);
Enter the url of the api using “POST” method in Postman. Go to Body>Raw>JASON
and input the data as per the JASON object.
Here we‟re going to save Sobia‟s data into the database.
Data currently present in the database:

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 32


ANKAJ SIR ACADEMY ADVANCE JAVA

List of all the leads after saving Sobia‟s data using Postman:

Deleting One Data:


To delete the data using web services we need to create a method in “LeadRestController.java”
@DeleteMapping("/delete/{id}")
//("/delete/{id}") so url will be localhost:8080/api/leads/delete/id#
public void deleteOneLead(@PathVariable("id") long id) {
leadService.deleteLeadById(id);
}
Enter the url of the api using “DELETE” method in Postman. Here we‟re going to delete Sobia‟s
data (id# 10), so ur will be “localhost:8080/api/leads/delete/10”

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 33


ADVANCE JAVA

List of all the


Leads after deleting Sobia’s data using postman: localhost:8080/updateLead

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 34


ADVANCE JAVA

Updating One Data:


To update the data using web services we need to create a method in “LeadRestController.java”
@PutMapping //used to update the data in the database
public void updateOneLead(@RequestBody Lead lead) {
//@RequestBody to read the data from the JSON Object & put it into Lead's Object
leadService.saveLead(lead);
}
Enter the url of the api using “PUT” method in Postman. url will be same as Saving the lead.
To update firstly get all the leads data as JSON object, pick one whose data needs to be
updated, Go to Body>Raw>JASON and paste & modify the data, then click on Send. Here we‟re
updating the ID#4: John‟s Last Name, Email & Mobile Number, ID Cannot be changed as it‟s a
Primary Key.

List of the all the leads after updating John‟s (ID#4) data:

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 35


ADVANCE JAVA
Q. What is the difference between Micro Services and Web Services.?
A. In Microservices we break bigger applications into smaller mini projects & then will establish
communication between them using Web Services.

Q. What is Monolithic Application?


A. In Monolithic architecture, all the features and coding is done in single place, and all the
systems store and consume data generally from a single location. In this approach, there is a
high level of coupling and maintenance is difficult.

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 36


ADVANCE JAVA

Getting One Lead Data using Id#:


To get one lead data using web services we need to create a method in
“LeadRestController.java”
@GetMapping("/leadinfo/{id}") //url will be localhost:8080/api/leads/leadinfo/id#
public Lead getOneLead(@PathVariable("id") long id) {
Lead lead = leadService.getOneLead(id);
return lead;
}
Enter the url of the api using “GET” method in Postman. Here we‟re going to get Mike‟s data
(id# 5), so ur will be “localhost:8080/api/leads/leadinfo/5”

All the CRUD Operations done using Postman also called as “Exposing of the data using Web
Services”.
Now Let‟s “Consume the data using Web Services” & build one project to search the lead data
using ID# & that project will run on another server port.
To build this part of the project we need the above built api (url):
“localhost:8080/api/leads/leadinfo/5”
Let‟s check this url in the browser:

Here we get the JSON object, based on that we‟ll start our project by creating the dto package
and a JAVA class matching to these variables because we have to copy the data from JSON
object to JAVA object.

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 37


ADVANCE JAVA

Key Key Key Key Key

Value (Long) Value (String) Value (String) Value (String) Value (Long)

Project name: “search_lead”


url: localhost:9090/search
package com.search_lead.dto;
public class Lead {
private long id;
private String firstName;
private String lastName;
private String email;
private long mobile;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getMobile() {
return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}
}

Created the “com.search_lead.dto” package and a “Lead.java” JAVA class matching to the JSON
Object because we have to copy the data from JSON object to JAVA object.

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 38


ADVANCE JAVA

Search Page (View Layer) “search_lead.jsp”


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Search</title>
</head>
<body bgcolor="lightyellow">
<form action="searchLead" method="post">
<table border=1>
<tr><th colspan="2" bgcolor="lightgrey"><font size="4"> SEARCH LEAD </font></th></tr>
<tr>
<td> <input type="text" name="id" placeholder="Enter the Lead ID#"/> </td>
<td> <input type="submit" value="Search" /> </td>
</tr>
</table>
</form>
</body>
</html>

Controller Layer: “SearchLeadController.java”


package com.search_lead.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.search_lead.dto.Lead;
import com.search_lead.services.SearchLeadService;
@Controller
public class SearchLeadController {
@Autowired
private SearchLeadService leadService;
@RequestMapping("/search")
public String viewSearchPage() {
return "search_lead";
}
@RequestMapping("/searchLead")
public String searchLeadById(@RequestParam("id") long id, ModelMap model) {
Lead lead = leadService.getLeadById(id);
model.addAttribute("l", lead);
return "leadinfo_result";
}
}

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 39


ADVANCE JAVA

Service Layer (Interface): “SearchLeadService.java”


package com.search_lead.services;
import com.search_lead.dto.Lead;
public interface SearchLeadService {
public Lead getLeadById(long id);
}

Service Layer (Class): “SearchLeadServiceImpl.java”


package com.search_lead.services;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.search_lead.dto.Lead;

@Service
public class SearchLeadServiceImpl implements SearchLeadService {

@Override
public Lead getLeadById(long id) {
RestTemplate rt = new RestTemplate(); //Built-in Class for consuming Web Services
Lead lead = rt.getForObject("http://localhost:8080/api/leads/leadinfo/"+id, Lead.class);
//take the json object & save in Lead Class
return lead;
}
}

Result Page (View Layer) “leadinfo_result.jsp”


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title> Search Result </title>
</head>
<body>
<table border=1>
<tr><th colspan="6" bgcolor="lightgrey"><font size="4"> SEARCH RESULT </font></th></tr>
<tr bgcolor="LightYellow">
<th>Id No.</th><th>First Name</th><th>Last Name</th><th>Email</th><th>Mobile</th></tr>
<tr>
<td style="text-align:center"> ${l.id} </td>
<td>${l.firstName}</td>
<td>${l.lastName}</td>
<td>${l.email}</td>
<td>${l.mobile}</td>
</tr>
</table>
</body>
</html>

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 40


ADVANCE JAVA
Search Result Page: (Browser)

Search Lead Application Properties.


#Path of the jsp file and its extension
spring.mvc.view.prefix=/WEB-INF/jsps/
spring.mvc.view.suffix=.jsp

#Server Port
server.port=9090

POM.xml (Dependency)
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>

Notes prepared by _M$A_ : [email protected] Click here to connect on WhatsApp 41

You might also like