Spring Boot Dec
Spring Boot Dec
==========
Dilip Singh
Work Ex : 11 Years :
Working in US based Product
Connect me at:
Linked In : @dilipsingh1306
Instagram : @DilipItAcademy
Mail : [email protected]
Youtube : @DilipItAcademy
-----------------------
Programing Lang :
-----------------
S/W : To make
Whatsapp
Insta
....
Send amount :
Bank
Visit Bank
Fil The Form
Standing Q
Deposit
Transfer Complted
4 Hours
Framework :
9154861173
int a =0 ;
int value = 0;
int values[] = {}
for(int i=0;){
Object :
obj.getEmpId();
Drive Link:
----------
https://drive.google.com/drive/u/0/folders/1QLg03lpRoIj8A0wNedhCfwKBrtxu6BO8
Jan : 03
========
Spring FW :
---------
Spring 2003
Spring Boot 2013
Spring FW :
----------
jar file :
Drive:
https://drive.google.com/drive/u/0/folders/1QLg03lpRoIj8A0wNedhCfwKBrtxu6BO8
ctrl+shift+t
Link: bit.ly/SBMS7AMDS
https://drive.google.com/drive/u/0/folders/1QLg03lpRoIj8A0wNedhCfwKBrtxu6BO8
Dependecy Injection:
When we are having dependecy of one Object into another Object, Conatiner
will provide the Dependecies.
4. Programming :
Do you know
How to Confugure?
1. XML Configuration
1. XML Configuration
======================
1. Create XMl file
1. BeanFactory <I>
2. ApplcationContext <I>
associated Implemenataion clsses.
Student Employee
main(){
Debugging : analyzing our source code at runtime level with real value.
. 11 : logic
Dependency Injection:
====================
A{
//methods
}
B{
A a = new A();
a.method();
A{
//methods
}
B{
A a;
a.method();
XML Config :
DI :
1. Setter Injection
2. Constructor Injection
Annotation/Java Config:
DI :
1. Setter Injection
2. Constructor Injection
3. Field Injection
XML Config :
DI :
1. Setter Injection
2. Constructor Injection
POJO Classes:
-------------
In java ,
primitive
byte
short
int
long
double
float
char
boolean
String
non-primitive
Classes
1. Pre-Defined Classes
Coding:
----------
package com.flipkart;
//3 properties
private int id;
private String productName;
private double price;
public Product() {
System.out.println(" Product Is Created.....");
}
==================================
id name price
0 null 0.0
======================================
1, phone, 150000
int id;
id = 10;
ProductId
productId;
setproductId
setProductId
isOrderSuccess
setIsOrderSuccess
setOrderSuccess
Order{
ArrayList<String> foodItemNames;
ArrayList :
Assignment :
List<Double> prices;
DO whatsapp
9293226789
9000994008
LIst<T>
Set<T> :
<property name="subjects">
<set>
<value>Java</value>
<value>python</value>
<value>java</value>
<value>CPP</value>
<value>C</value>
<value>C</value>
<value>CPP</value>
</set>
</property>
-----------------------------
Map :
key-value :
exp Year , man year, Name , price , company, conatct, email of Product
COmpany.
Define an Order :
https://drive.google.com/file/d/1FnbtP3yqjTN5arlEGeoUHCrIJcdcBgM7/view?
usp=drive_link
After Download
Constructor Injection:
----------------------
p.set....
<constructor-arg>
<list>
<value>Poori</value>
<value>Dosa</value>
<value>Poori</value>
<value>Idly</value>
</list>
</constructor-arg>
<constructor-arg>
<set>
<value>Poori</value>
<value>Dosa</value>
<value>Poori</value>
<value>Idly</value>
</set>
</constructor-arg>
Employee{
Address address;
a1 : Address
a2 : Address
e1: Employee
COnatiner will identify dependecny bean objects and injects Bean objects based on
auto wiring configuration.
2. byName :
autowire = byName
3. byType
autowire = byType
Transaction ;
4. constructor
autowire=constructor
Transaction : t1
p1 t1
public Order(Product product, Transaction transaction) {
t1
public Order(Transaction transaction) {
super();
this.transaction = transaction;
}
int i;
int i=0;
Bean Scopes:
============
singleton
prototype
request
Deployed : Server :
UserLogin
session : HttpSession
application:
1. Spring Project
2. Create java CLass
How ever we configured in XML file wikt bean id and class , similarly
inside Configuration class,
we are going to write method whichh are returing Bean Object and
those are annoatated with @Bean annotaions.
@Bean annotaions:
----------------
@Component:
----------
So that, Spring Conatiner, scans all @Component classes and creates Bean objects
fro very component class while are loading application.
@ComponentScan:
===============
As Part of this annotaion, we are going to provide, The package names of where we
written Component classes.
Employee{
}
One
Two
Three
...
...
Hundred
@Component :
If we are not given any value in side @Component , the Class name is Bean Id
but First word given as lower case by Conatiner.
Products{
Products product
StudentDetails : studentDetails
Bean Wiring:
=============
https://www.samsung.com/
samsung :
Infosys :
Samsung
galaxyai
com.samusung.galaxyai.user
com.samusung.galaxyai.mobiles
com.samusung.galaxyai.mobiles.galxy
com.samusung.galaxyai.tab
@Bean : If Bean Id provided , that will be given as Bean ID by Conatiner
If Not Provided , method name will be taken as Bean Id and assigned to Objetc.
---------
Req : Prescription{
String drugName
Double price
Create Only one bean Object with user defeined data of Properties.
Req :
1. Constrcutor parameter
2. register() with refresh()
3. scan() , method
=========================================
Bean Scopes:
============
1. singleton
2. prototype
3. request
4. session
5. application
DI with Annotations:
---------------------
Emp{
Address address;
Emp(Address address){
setAddress(){
@Qualifier:
-----------
@Primary :
This annoatiaon should be used when a bean Object shpuld be injected b y default
when we are not specified @Qualifier with @Autowired.
A, B :
A{
@Autowired
B b;
}
B: 1 Bean Object
Interface : One
One o2 = new Two(); Valid : Interface can refer impl class Object.
Interface : One
Two {
One o1;
}
Xyz{
One o1;
One o2;
Xyz{
Component :
Zoo:
animal.getName();
DI will be failed ,
==================================================================
Spring Boot :
=============
1. Creating Project
2. Doenload/Get The jar file of Spring FW
3. Configuring jar files with our project
jar files added at class path :
4. Writing Programs
5. XML/annoataions : Bean Objects
6. Getting Bean Object from the Conatiner.
URL : https://start.spring.io/
Maven :
Maven Goals:
Gradle
// https://mvnrepository.com/artifact/org.springframework/spring-core
implementation group: 'org.springframework', name: 'spring-core', version: '5.3.29'
Spring Initilizer :
They Customized EClipse for the Spring Boot Application Devlopment Environment.
@SpringBootApplication:
XML Config.
Create Employee and Address beans and make Sure Employee is Created and Injected
with reference of Address.
com.naresh.netbanking.one
com.naresh.two.one
com.three
com.naresh.netbanking.one.four
@SpringBootApplication :
@EnableAutoConfiguration:
@SpringBootApplication :
This annoataion is enabling Component scan Functionlity.
Spring FW :
1. Java Prtoject
2. Add Jars
3. Creat Java File : Student : Component
4. Creating Configuration Class: Inside Defined @ComponentScan
@Bean Method
5. Creating Conatiner
AnnotationConfigAppContext context = new
AnnotationConfigAppContext();
context.register(SpringBootExamplesApplication.class
Class); // Configuration Classes
Spring Boot :
1. Prtoject
3. Creat Java File : Student : Component
5. Creating Conatiner
basePackage: com.dilip.spring.boot
com.dilip.spring.boot.one
Employee
com.dilip.spring.boot.ddjkfdjf.sdfjfkjdsfjkjk
com.dilip :
Employee
Req:
2 Employee Objects :
@Component
Emp{
@Bean : Emp
@COpmonent
Org{
@Qualifier
@Autowired
Emp employee;
}
1. we can define COnfiguration Classes under base package, the Spring Boot
Implicitly scans Configuration classes automatically.
Ctrl+shft+T
Description:
emp : employee,employeeTwo
@Autowired
private Employee emp;
Org{
@Autowired
private Employee employee;
}
When we have more than one Dependecy Object of Dependency Type, Internally IOC
conatiner verifies
if(declared)
@Qualifier, @Primary
@Qualifier : Respective Bean Object injected.
@Primary :
When no @Qualifier is prested , then Respective primar marked
Bean Object injected.
if(not declared)
IOC conatiner, By Name functionality.
none
byName
byType
constructor
@Value :
constructor injection
***************************
APPLICATION FAILED TO START
***************************
Description:
Action:
========
as part @Value, we are configuring real values which are passed as constructor
args.
@Value:
----------
to initilize values to properties.
@Value
id
name
salary
employee
id=0
name=null
salary=0.0
id=100
name=Dilip
salary=88888
@Component
class DbConnection{
url
name
pwd
}
DbConnection:
url=null
name=null
pwd=null
url=localhost:1521
name=dilip
pwd=dilip
10 classes :
@Value("localhost:1521:XE")
private String url;
@Value("dilip")
private String userName;
@Value("dilip")
private String password;
20 Places
2nd approach :
url=localhost:1521
username=dilip
password=dilip
@Value("url")
private String url;
@Value("userName")
private String userName;
@Value("password")
private String password;
20 classes
password chnaged to : dilip => abc1234
syntax :
@Value("${key-name}")
proerty name
properties files,
BookMyShow{
String
int
Double
booolean
NetBanking
username
pwd
CreditCard
number
cvv
=========
Bean Object :
........
#
com.dilip.spring.boot.orders.Order@2679311f
Utilized Bean Objects of Order : com.dilip.spring.boot.orders.Order@2679311f
1111
com.dilip.spring.boot.orders.Order@2e34384c
Utilized Bean Objects of Order : com.dilip.spring.boot.orders.Order@2e34384c
1111
===========================
1. By Using Interface
InitializingBean : Interface :
only one
DisposableBean : Interface
only one
2. By Using Annotations
-> We can Define methods with any name , and those methods
we are going to annotate based on initilization and dispose functionality.
@PostConstruct : initilization
@PreDestroy : Distruction
Assignemnt :
XML :
Runners Logic will be executed only once when we are starting our application.
By Using Runners, We can execute a logic right After Spring Application Context is
Ready.
2 Runners we have :
1. CommnadLineRunner
Command Line Arg values are passing as array of values :
ApplicationArguments
2. ApplicationRunner
Command Line Arg values are passing as an Object :
ApplicationArguments
Req :
Flipkart :
Order is Created
Product is Created.
Runner One IS Created...
Runner1
Runner2
Runner3
Runner4
Runner5
Same Order :
RunnerFour : 1
RunnerOne : 3
RunnerTwo : 2
JDBC API :
JDBC Steps:
Select Query
2. Connection Object :
URL
USER NAME
PASSWORD
Statement :
4. Execution Of Query :
5. Closing Connection
2. Connection Object :
URL
USER NAME
PASSWORD
Statement :
insert Query
4. Execution Of Query :
5. Closing Connection
1000 Times :
===================
URL
USER NAME
PASSWORD
Statement :
Statement :
Select/update/insert Query
4. Execution Of Query :
-------
Abc{
@Autowired
DbStatement stamt; //Stament Object
stamt. Select
}
XYZ{
@Autowired
DbStatement stamt; //Stament Object
stamt insert
JdbcTemplate :
-------------
Abc{
@Autowired
JdbcTemplate template;
XYZ{
@Autowired
JdbcTemplate template;
template.update(insert i);
Project Setup :
--------------
1. Spring Boot :
Dependency :
Spring Data JDBC
Driver jar file : orcale driver/ my Sql
2. Configure DB Details :
URL : jdbc:oracle:thon@localhost:1521:orcl
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=c##dilip
spring.datasource.password=dilip
================================
DB install:
Downlaod SQLDeveloper'
SQL Devloper :
+ New Connection
Connnection Name
user name of Your DB
password
Url port
service ID
Test : Success
Save
EClipse VS IntelliJ
Dbeaver
========================================
Table : Notifications
Req : insert :
Query :
Spring JDBC :
@Value("${spring.datasource.password}")
======================
==============================
Positional Parameters :
==========
"INSERT INTO NOTIFICATIONS values('EMAIL','[email protected]', 'Email Notification')"
Table is ready
Query :
Select Operations :
==================
Row MApper :
----------
Pojo class :
=====> make sure java property data type is matching to table column data types
long emp_id
String name
String email
double salary;
// After executing select Query, once Getting RS, pleae map result set
data to List of Objects belongs to type EmployyeDetails
Order{
Assignment :
===========
column names:
1. Insert Data
2. Update /Delete
3. Select Query :
List Of Records ;
//override
mapRow()
{
Rs : ordr_dtl_id : Pojo : orderDetailId
================================
===================================================================================
==============================================================
JPA:
Specification :
ORM :
Finish
Add Properties :
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=c##dilip
spring.datasource.password=dilip
2. Create a Db table
==================================
1. Entity classes:
===================
@Column :
This annotaion will be used at property level.
@Id:
----
1. CrudRepository
2. JpaRepository
@Entity
@Table(name = "Order_Details")
public class OrderDetails {
@Id
@Column(name = "oid")
private int orderId;
@Column(name = "email")
private String emailId;
@Column(name = "name")
private String name;
@Column(name = "no_of_items")
private int noOfItems;
@Column(name = "amount")
private double amount;
@Column(name = "city")
private String city;
@Column(name = "gender")
private String gender;
----------------
delete order id is : 1 :
======================================
===============
Hibernate: select
od1_0.oid,od1_0.amount,od1_0.city,od1_0.email,od1_0.gender,od1_0.name,od1_0.no_of_i
tems from order_details od1_0 where od1_0.oid=?
Hibernate: select
ud1_0.user_id,ud1_0.age,ud1_0.city,ud1_0.contact,ud1_0.email,ud1_0.gender,ud1_0.nam
e from user_details ud1_0
Hibernate: select
ud1_0.user_id,ud1_0.age,ud1_0.city,ud1_0.contact,ud1_0.email,ud1_0.gender,ud1_0.nam
e from user_details ud1_0 where ud1_0.user_id=?
JpaRepository V/S CrudRepository:
-----------------------------------
JpaRepository : Child
CrudRepository : Parent
JpaRepository given functionalities to perform Crud Operations anong with that This
one provided fetures
Sorting and Paginataion
Req :
Data based in City Name
select * from users where city='HYD'
By using JPA custom findByMethods, we can define our own findBy methods based on
coulumns of a table.
Synatx :
findBy<PropertyNameOfEntityWhichIsRepresetningTableCoulmn>(DataTypeOfPropertyFromEn
tityClass paramNames...);
Note : We have to make sure Property Name First Character Should be Capital Letter.
city : City
fisrtName;
findBycity : Invalid
findByCity : Valid
findByFisrtName
findByCity(....)
int year;
findByYear(short year)
Hibernate: select
ud1_0.user_id,ud1_0.age,ud1_0.city,ud1_0.contact,ud1_0.email,ud1_0.gender,ud1_0.nam
e from user_details ud1_0 where ud1_0.city=?
Req :
FEMALE in HYD
select
ud1_0.user_id,ud1_0.age,ud1_0.city,ud1_0.contact,ud1_0.email,ud1_0.gender,ud1_0.nam
e from user_details ud1_0 where ud1_0.city=? and gender=?
Hibernate: select
ud1_0.user_id,ud1_0.age,ud1_0.city,ud1_0.contact,ud1_0.email,ud1_0.gender,ud1_0.nam
e from user_details ud1_0 where ud1_0.city=? and ud1_0.gender=?
By Using Proxy Design Pattern they are provdining implementation at runtiime and
creating an instance and injected into interface reference.
============================
==================================
1. If Table name and Entity Class Name , both are same , then it's optional to
define @Table annoataions
-> similarly, When Column names and Property names are same, then @Column Optional.
--------------------------------------------
===============================================
JPA providing like we can genearte table inside Database with help of entity
classes.
Req :
PatientSummary
-------------:
pid
fname
lname
email
gender
contact
spring.jpa.hibernate.ddl-auto=
2. validate :
validation will happens wheather table presented or not w.r.to every entity
class and table details defined inside entity class.
3. update
JPA validates table presented or not w.r.to every entity class and
table details defined inside entity class.
4. create
JPA will drops all the tables associated to entity classes and then newly
agaian tables are created by JPA FW.
while terminating app execution tables are droped or not? Not Dropped
5. create-drop:
JPA will drops all the tables associated to entity classes and then newly
agaian tables are created by JPA FW, when application getting tterminated or
stopped, tbales will be dropped.
Lombok:
------
Update operations :
-----------------
Hibernate: select
u1_0.id,u1_0.email,u1_0.is_selected,u1_0.name,u1_0.salary,u1_0.year from
interview_users u1_0 where u1_0.id=?
Feb-26:
=======
Native SQL Queries execution :
------------------------------
Steps:
------
1. Define a abstract method inside Repository Interface.
3. JPA provided an annotation called as @Query to define , which SQl Query has to
be executed inside DB.
Hibernate: select
u1_0.id,u1_0.email,u1_0.is_selected,u1_0.name,u1_0.salary,u1_0.year from
interview_users u1_0
Req :
-----
==================================
2 ways :
======================================
By Using Index Postional Params, we have to define index with ? where we want to
pass the Data.
index: Numbers
Syntax : ?<indexNumber>
Ex :
?1
@Transactional
@Modifying
DML :
Req : select * fom user_details where city=.... and gender=...
Syntax: :<nameOfThePosition>
Ex :gender
:cityName
@Param :
cityName : @Param
gender : @Param
DML Query :
============
JPQL:
----
Sorting:
=======
JPA :
findAll(Sort.by("userId"))
select
ud1_0.user_id,ud1_0.age,ud1_0.city,ud1_0.contact,ud1_0.email,ud1_0.gender,ud1_0.nam
e from user_details ud1_0 order by ud1_0.user_id
Hibernate: select
ud1_0.user_id,ud1_0.age,ud1_0.city,ud1_0.contact,ud1_0.email,ud1_0.gender,ud1_0.nam
e from user_details ud1_0 order by ud1_0.user_id
Hibernate: select
ud1_0.user_id,ud1_0.age,ud1_0.city,ud1_0.contact,ud1_0.email,ud1_0.gender,ud1_0.nam
e from user_details ud1_0 order by ud1_0.user_id desc
userDetailsRepository.findAll(Sort.by(Direction.DESC, "userId"))
// NOTE : Sort class by method take entity Properties not column names.
Hibernate: select
ud1_0.user_id,ud1_0.age,ud1_0.city,ud1_0.contact,ud1_0.email,ud1_0.gender,ud1_0.nam
e from user_details ud1_0 offset ? rows fetch first ? rows only
Order
ordr_id pK : ID :
amount
noOFItems
etcc..
@GeneratedValue:
===============
@GeneratedValue: :
SEQUENCE : Oracle
2. IDENTITY :
3. SEQUENCE
4. TABLE
create table
my_test
(
id number default my_test_id_seq.nextval,
name varchar(10)
);
TASK :
File :
abc | sdhshd | 233v| sdfdf| 23-4-2024132323 |
Entity Class :
acde070d-8c4c-4f0d-9d8a-162843c10333
7f387fda-1dc5-49ec-a947-5075ff91ab6b
Defined Between Tables like, When Parent Table having one record the assciated
child table should allow only one record for that parent record.
@OneToOne
Hibernate: create table emp_address (aid number(10,0) not null, city varchar2(255
char), country varchar2(255 char), pincode number(10,0) not null, state
varchar2(255 char), primary key (aid))
Hibernate: create table emp_dtl (emp_id number(10,0) not null, email varchar2(255
char), gender varchar2(255 char), name varchar2(255 char), address_aid
number(10,0), primary key (emp_id))
Joining Columns :
====================
Hibernate: select
e1_0.emp_id,a1_0.aid,a1_0.city,a1_0.country,a1_0.pincode,a1_0.state,e1_0.email,e1_0
.gender,e1_0.name from emp_dtl e1_0 left join emp_address a1_0 on
a1_0.aid=e1_0.address_aid where e1_0.emp_id=?
=================================
Pesrsist : Save
@OneToOne(cascade = CascadeType.ALL)
Hibernate: select
e1_0.emp_id,a1_0.aid,a1_0.city,a1_0.country,a1_0.pincode,a1_0.state,e1_0.email,e1_0
.gender,e1_0.name from emp_dtl e1_0 left join emp_address a1_0 on
a1_0.aid=e1_0.address_aid where e1_0.emp_id=?
Verifying
select
e1_0.emp_id,a1_0.aid,a1_0.city,a1_0.country,a1_0.pincode,a1_0.state,e1_0.email,e1_0
.gender,e1_0.name from emp_dtl e1_0 left join emp_address a1_0 on
a1_0.aid=e1_0.emp_add_id where e1_0.emp_id=?
One-Many : 1:N
===============
This mapping is defined as when parent is having one record , from associatec chile
table level we are going to maintain many records for that one record of parent.
Hibernate: create table emp_dtl (emp_id number(10,0) not null, email varchar2(255
char), gender varchar2(255 char), name varchar2(255 char), primary key (emp_id))
===================
Hibernate: select
e1_0.emp_id,e1_0.email,e1_0.gender,e1_0.name,a1_0.emp_dtl_emp_id,a1_1.aid,a1_1.city
,a1_1.country,a1_1.pincode,a1_1.state from emp_dtl e1_0 left join emp_dtl_address
a1_0 on e1_0.emp_id=a1_0.emp_dtl_emp_id left join emp_address a1_1 on
a1_1.aid=a1_0.address_aid where e1_0.emp_id=?
Students Vs Course
100 : JAVA
Employees Vs Dept :
Hibernate: create table dept (dept_id number(10,0) not null, dept_name varchar2(255
char), primary key (dept_id))
Hibernate: select
e1_0.emp_id,d1_0.dept_id,d1_0.dept_name,e1_0.email,e1_0.gender,e1_0.name from
emp_dtl e1_0 left join dept d1_0 on d1_0.dept_id=e1_0.emp_dept_id where
e1_0.emp_id=?
Hibernate: select
e1_0.emp_id,d1_0.dept_id,d1_0.dept_name,e1_0.email,e1_0.gender,e1_0.name from
emp_dtl e1_0 left join dept d1_0 on d1_0.dept_id=e1_0.emp_dept_id where
e1_0.emp_id=?
Hibernate: insert into dept (dept_name,dept_id) values (?,?) -> 11, ENG
Many to Many :
==================
Hibernate: create table emp_dtl (emp_id number(10,0) not null, email varchar2(255
char), gender varchar2(255 char), name varchar2(255 char), primary key (emp_id))
Hibernate: create table roles (id number(10,0) not null, name varchar2(255 char),
primary key (id))
===============
Hibernate: select
e1_0.emp_id,e1_0.email,e1_0.gender,e1_0.name,r1_0.emp_dtl_emp_id,r1_1.id,r1_1.name
from emp_dtl e1_0 left join emp_dtl_roles r1_0 on e1_0.emp_id=r1_0.emp_dtl_emp_id
left join roles r1_1 on r1_1.id=r1_0.roles_id where e1_0.emp_id=?
MVC?
M - Model
V - View
C - Controller
Spring Web in our projects, we ahve to make sure following MVC arch..
===================
Spring Web Application:
=======================
app 1 :
app 2
app 3
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=c##dilip
spring.datasource.password=dilip
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
/helloworld
/make/payment
Spring Boot :
/helloworld
/xyz
/mno
/user
/login
localhost:8080/abc/helloworld
localhost:8080/abc/xyz
localhost:8080/abc/mno
=================================================
=============================
Configuring where our view files are located on Project Folder Structure
2. View Resolver :
Add Below Dependency ibn POM>xml, Integrted Tomcat is not supporting JSP
functionlaites.
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-
embed-jasper -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
We have to configure , V
Controller:
===========
Controller is a Java class, but we are annotating with a special annotation called
as @Controller.
Servlets :
@WebServlet(/welocme)
WelcomeServlet extends httpServlet{
service()
{
// jsp file s
welome.jsp
/hello
/wel
URL formation :
localhost:9999/flipkart/welcome
localhost:9999/flipkart/welome ->
Practice : https://www.baeldung.com/spring-boot-jsp
2 Controller : 4 mtohods
-->
Many Controllers : Many Request Mapping URI's
Internally , How Spring Web Module identifying respective controller method out of
many conttrolers and request mapping method.
doPOST(HttpServeltRequeest, Response){
request.getParametert //
//all data came
3. Can we maintian, same HTTP method and PATh values same for two different
Controller Methods?
One{
/hello GET
req1(){
}
GET
}
localhost:8080/flipkart/hello
Two{
/hello POST
req2(){
}
}
Spring Web Module is impleneted by using a concept called Front Controller Design
pattern
Front Controller ?
Controller?
Request+Handle+Mapping
when we are deploying , Spring Web Application , Internally Spring will scan all
controller classes.
Service Layer/Class:
=====================
-----------
======================================================
Web Services :
============
XML Protocol
REST API/Services :
=================
Project Setup :
---------------
1.
localhost:9999/rest-api/hello
localhost:9999/rest-api/order/info
@ResponseBody :
This annotation , will make the return value converted as a response value and
sended to the Client.
Annotation that indicates a method return value should be bound to the web response
body.
@RestController :
===================
RestController:
For verifying existing REST services functionlity, we are taking help of REST API
Testing Tools.
POSTMAN :
--------
Insomnia:
----
POSTMAN :
---------
S/w : Download :
@RequestMapping(path="/hello")
public String registerUSer() {
Runtime
Method Not alloed
Registration Success
localhost:9999/rest-api/order/info
localhost:9999/rest-api/update/order PUT
===============
@PostMapping:
Annotation for mapping HTTP POST requests onto specific handler methods.
Specifically, @PostMapping is a composed annotation that acts as a shortcut for
@RequestMapping(method = RequestMethod.POST).
XML :
<user>
<name>Dilip</name>
<email>[email protected]</email>
<password>dilip1111</password>
<contact>2123232</contact>
</user>
user.xml
JOSN :
XML Vs JSON ?
-> As Part oF REST API impl, we can use either XML or JSON or Both also to
exchange Data in between applications.
JSON :
------
<user>
<name>Dilip</name>
<email>[email protected]</email>
<password>dilip1111</password>
<contact>2123232</contact>
</user>
XML
-> JOSN Data Fromat Contains Concepts of JSON Object, JSON Arrays, JSON
Properties.
JSON : name:Dilip
<user>
<name>Dilip</name>
<email>[email protected]</email>
<password>dilip1111</password>
<contact>2123232</contact>
</user>
<user>
<name>Naresh</name>
<email>[email protected]</email>
<password>diliwerrerrep1111</password>
<contact>3333</contact>
</user>
XML
<user>
<name>Dilip</name>
<email>[email protected]</email>
<password>dilip1111</password>
<contact>2123232</contact>
<marks>
<sub1>11</sub1>
<sub2>22</sub2>
<sub3>33</sub3>
<sub4>44</sub4>
</marks>
</user>
JSON
"name" : "Dilip",
"email": "[email protected]",
"password" : "dilip1111",
" contact" : 2123232,
"marks" : {
"sub1" : 11,
"sub2" :22,
"sub3" : 33,
"sub4" : 44
}
}
JSON :
============
JSON Object:
=============
"name" : "Dilip",
"email": "[email protected]",
"password" : "dilip1111",
" contact" : 2123232
"name" : "Dilip",
"email": "[email protected]",
"password" : "dilip1111",
" contact" : 2123232
},
{
"name" : "Dilip",
"email": "[email protected]",
"password" : "dilip1111",
" contact" : 2123232
}
,
{
"name" : "Dilip",
"email": "[email protected]",
"password" : "dilip1111",
" contact" : 2123232
"name" : "Dilip",
"email": "[email protected]",
"password" : null,
" contact" : 2123232,
"address" : {
"sub1" : 11,
"sub2" :22,
"sub3" : 33,
"sub4" : 44
}
}
JSON Arrays :
=================
Java :
Studemt{
int id;
String name;
HTTPMessageConverters:
=======================
payload :
========
Request?response content will be called a payloads.
1. A REST Service can support more than one data formats as Requeet and Response.
-> 4 Properties
name
email
password
contact
-> JSON
Step 1:
JSON Payload/Body
name
email
password
contact
{
"name" : "Dilip",
"email" : "[email protected]",
"password" : "dilip1111"
"contact" : 8283283823
}
UserDetails{
name
email
password
contact
XML
-> To convert JSON payload of Request Body coming from Cleint to Our Server
Application,
we ahve to use an annotation @RequestBody at method parameter level in controller
method associated to JAva Class , which Object we are expexting.
@PostMapping(path = "/user/create",
consumes = MediaType.APPLICATION_JSON_VALUE, produces =
MediaType.APPLICATION_JSON_VALUE)
public String userRegistration(@RequestBody UserDetailsRequestDto
userDetails) {
URL : localhost:9999/flipkart/user/create
Body : Yes
JSON Payload :
{
"name" : "Dilip",
"email" : "[email protected]",
"password" : "dilip1111",
"contact" : 8283283823
}
Postman :
{
"name": "Dilip",
"email": "[email protected]",
"password": "Dilip1111",
"contact": 2123232,
"address": {
"city": "HYD",
"area": "AMPT",
"state": "TG",
"pincode": 500072
},
education{
"subjects" : ["English","Hindi","Maths"]
}
employment{
Company Name
Start Year
End year
Designation
}
}
Java Classes :
REST Service ;
======
College{
name;
branchCode
Student{
name
id
mobile
Address{
city
area
}
}
Req -> Analyze -> Design -> Request Fromat -> JSON -> JSON mapping Pojos.
Details
Personal Info
address
-> education
standard :
Name Of Org :
passed Year:
avgPercentage :
standard :
Name Of Org :
passed Year:
avgPercentage :
standard :
Name Of Org :
passed Year:
avgPercentage :
JSON :
{
"name": "Dilip",
"email": "[email protected]",
"password": "Dilip1111",
"contact": 2123232,
"address": {
"city": "HYD",
"area": "AMPT",
"state": "TG",
"pincode": 500072
},
"educationData" : [
{
"standard": "10",
"nameOfOrg" : "ABC",
"passedYear": 2003,
"avgPercentage" : 76.77
},
{
"standard": "intermediate",
"nameOfOrg" : "XYZ",
"passedYear": 2005,
"avgPercentage" : 80.77
},
{
"standard": "Graduation",
"nameOfOrg" : "PQR",
"passedYear": 2009,
"avgPercentage" : 66.66
}
]
}
JAVA :
===============================================================================
https://restful-api.dev/
PhoneDetails
id
name
PhoneData data;
PhoneData
color
capacity
==========================
[
{
"id": "1",
"name": "Google Pixel 6 Pro",
"data": {
"color": "Cloudy White",
"capacity": "128 GB"
}
},
{
"id": "2",
"name": "Apple iPhone 12 Mini, 256GB, Blue",
"data": null
},
{
"id": "3",
"name": "Apple iPhone 12 Pro Max",
"data": {
"color": "Cloudy White",
"capacity GB": 512
}
},
{
"id": "4",
"name": "Apple iPhone 11, 64GB",
"data": {
"price": 389.99,
"color": "Purple"
}
},
{
"id": "5",
"name": "Samsung Galaxy Z Fold2",
"data": {
"price": 689.99,
"color": "Brown"
}
},
{
"id": "6",
"name": "Apple AirPods",
"data": {
"generation": "3rd",
"price": 120
}
},
{
"id": "7",
"name": "Apple MacBook Pro 16",
"data": {
"year": 2019,
"price": 1849.99,
"CPU model": "Intel Core i9",
"Hard disk size": "1 TB"
}
},
{
"id": "8",
"name": "Apple Watch Series 8",
"data": {
"Strap Colour": "Elderberry",
"Case Size": "41mm"
}
},
{
"id": "9",
"name": "Beats Studio3 Wireless",
"data": {
"Color": "Red",
"Description": "High-performance wireless noise cancelling headphones"
}
},
{
"id": "10",
"name": "Apple iPad Mini 5th Gen",
"data": {
"Capacity": "64 GB",
"Screen size": 7.9
}
},
{
"id": "11",
"name": "Apple iPad Mini 5th Gen",
"data": {
"Capacity": "254 GB",
"Screen size": 7.9
}
},
{
"id": "12",
"name": "Apple iPad Air",
"data": {
"Generation": "4th",
"Price": "419.99",
"Capacity": "64 GB"
}
},
{
"id": "13",
"name": "Apple iPad Air",
"data": {
"Generation": "4th",
"Price": "519.99",
"Capacity": "256 GB"
}
}
]
==============================================================
Swagger is going to scan all Controller classes, and finds all REST services, it
will strt making a dcoument by reading Annotations inforamtion.
Add Dependecy of Swagger API to our project.
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.1.0</version>
</dependency>
-->
localhost:<port-number>/<context-path>/swagger-ui.html
localhost:9999/flipkart/swagger-ui.html
http://localhost:9999/flipkart/swagger-ui/index.html
https://www.youtube.com/@dilipitacademy
https://github.com/dilipsingh1306/SpringBoot-React-Integration
From SB -> Other App REST Services:
PATH Variables:
---------------
File Path:
URI Path:
URI PATH :
Place Holder : Holding the Place :
/users/{ResourceIdVaribaleName}
https://linkedin.com/in/{userID}
https://linkedin.com/in/dilipsingh1306
https://linkedin.com/in/naresh12345
https://linkedin.com/in/pawan143
https://linkedin.com/in/ankita-java-pro
https://www.instagram.com/{userid}
https://www.instagram.com/dilipsingh_1306
Req:
RequestBody:
{
"city":"HYD",
"gender":"MALE"
POJO
PATH VAriables
Assignment : Update :
RequestBody:
JSOn -> POJO
current Password : dilip123
new password : dilip999
Analysis :
============
https://www.flipkart.com/{category}
https://www.flipkart.com/mobile-phones-store
https://www.flipkart.com/grocery-supermart-store
localhost:9999:flipkart/users
Query/Request Parameters:
=========================
Quetsioning
Parameters :
Req :
Passing two String value, and getting single String value with Space concatnation
}
String fullName = getFullName(null, "Dilip"); -> NullpointerEXception
String fullName = getFullName("Java", "Dilip"); -> Java Dilip
String fullName = getFullName("", ""); ->
String fullName = getFullName("Java", "Dilip"); -> Java Dilip
Query String :
------------
Query Parameters:
================
Query String:
Syntax
localhost:9999/flipkart/users?key1=value1&key2=value2.....
localhost:9999/flipkart/users/info?city=hyd&gender=male
localhost:9999/flipkart/users/{city}/{gender}
localhost:9999/flipkart/users/hyd/male
Query Params:
localhost:9999/flipkart/users/info?city=HYD&gender=FEMALE
localhost:9999/flipkart/users/info?city=HYD&gender=FEMALE
localhost:9999/flipkart/users/{city}/{gender}
localhost:9999/flipkart/users/hyd/male
https://www.flipkart.com/
https://www.flipkart.com/mobile-phones-store
https://www.flipkart.com/grocery-supermart-store?marketplace=GROCERY&fm=neo
%2Fmerchandising&iid=M_00864b16-c508-4556-ad08-
0ad83f0e0460_1_372UD5BXDFYS_MC.CBUR1Q46W5F1&otracker=hp_rich_navigation_1_1.navigat
ionCard.RICH_NAVIGATION_Grocery_CBUR1Q46W5F1&otracker1=hp_rich_navigation_PINNED_ne
o%2Fmerchandising_NA_NAV_EXPANDABLE_navigationCard_cc_1_L0_view-
all&cid=CBUR1Q46W5F1
https://www.flipkart.com/mobile-phones-store?fm=neo%2Fmerchandising&iid=M_0c1c566e-
ca1d-4683-a42d-
89fe34d1cecc_1_372UD5BXDFYS_MC.ZRQ4DKH28K8J&otracker=hp_rich_navigation_2_1.navigat
ionCard.RICH_NAVIGATION_Mobiles_ZRQ4DKH28K8J&otracker1=hp_rich_navigation_PINNED_ne
o%2Fmerchandising_NA_NAV_EXPANDABLE_navigationCard_cc_2_L0_view-
all&cid=ZRQ4DKH28K8J
https://www.flipkart.com/search?
q=mobiles&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off
https://www.flipkart.com/search?
q=mobiles&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off
&p%5B%5D=facets.brand%255B%255D%3DApple
https://www.flipkart.com/search?
q=mobiles&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off
&p%5B%5D=facets.brand%255B%255D%3DApple
/products/{category}
/products/mbiles
brand
stiage
10 : HYD
4 _FEMAL
6-MAle
Categories:
Mobiles
Appliainces
Laptops
Grocery
etcc..
100
Req :
Filters
price
lowest price
highest price
ratings
flipakrt.com/mobiles?price=..&brand=...
-> Mobiles
Lpatops
flipakrt.com?category=<>
lapatops
->
Qualification : PG
Age
dob Year
users
-> age
-> qualifcation
All HTTP response status codes are separated into five classes or categories.
100 : continue
101 : switching Protocols
102
2xx successful – the request was successfully received, understood, and accepted
200
201
202
203
etc...
User Already Existed Id : EmailId existed, Try with New One : 200 Ok
3xx redirection – further action needs to be taken in order to complete the request
4xx client error – the request contains bad syntax or cannot be fulfilled
5xx server error – the server failed to fulfil an apparently valid request
ResponseEntity :
By ResponseEntity, we can bind Response Staus Codes and Actual Response Body.
HttpStatusCode Interface :
This will conatain all HTTP status Code as Static and Final variables.
HttpStatus Enum :
This is all Constant Values of All HTTP Sttaus Codes.
/user/""
email existed :
Send Data
email Not existed
Not existed, Try With new mail id
else{
return Respone : Invalid EmaolId Value, Please check Your rmaild.
}
200 OK
201 Created
401 Unauthorized
403 Forbidden
415 UnSupportedMediaType
"email": "[email protected]", *
"password": "GetSuresh1212122", * min 5 max 50
"contact": 765454444, * max 50 :
optional :
"city" :"BANG",
"gender" : "MALE"
Step 1
Add this Spring Boot Validation Starter to pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Step 2 :
Step 3 :
Inside Request Bodt, adding validation constraints to each and every individual
properties
Response {
name size must be between 5 and 50
Array : 1,2,3,4
[4] : 5
Exceptions :
{
"timestamp": "2024-04-04T02:36:22.686+00:00",
"status": 500,
"error": "Internal Server Error",
"trace": "java.lang.ArithmeticException: / by zero\r\n\tat
com.dilip.spring.boot.rest.api.controller.LoanController.getEMIValue(LoanController
.java:24)\r\n\tat
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\
tat
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessor
Impl.java:77)\r\n\tat
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethod
AccessorImpl.java:43)\r\n\tat
java.base/java.lang.reflect.Method.invoke(Method.java:568)\r\n\tat
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHan
dlerMethod.java:259)\r\n\tat
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(Invo
cableHandlerMethod.java:192)\r\n\tat
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod
.invokeAndHandle(ServletInvocableHandlerMethod.java:118)\r\n\tat
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.
invokeHandlerMethod(RequestMappingHandlerAdapter.java:920)\r\n\tat
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.
handleInternal(RequestMappingHandlerAdapter.java:830)\r\n\tat
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(Abst
ractHandlerMethodAdapter.java:87)\r\n\tat
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java
:1089)\r\n\tat
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:
979)\r\n\tat
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.ja
va:1014)\r\n\tat
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:903)\
r\n\tat jakarta.servlet.http.HttpServlet.service(HttpServlet.java:564)\r\n\tat
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885)
\r\n\tat jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterC
hain.java:205)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.jav
a:149)\r\n\tat
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterC
hain.java:174)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.jav
a:149)\r\n\tat
org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContext
Filter.java:100)\r\n\tat
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.j
ava:116)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterC
hain.java:174)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.jav
a:149)\r\n\tat
org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter
.java:93)\r\n\tat
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.j
ava:116)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterC
hain.java:174)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.jav
a:149)\r\n\tat
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEn
codingFilter.java:201)\r\n\tat
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.j
ava:116)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterC
hain.java:174)\r\n\tat
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.jav
a:149)\r\n\tat
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)
\r\n\tat
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)\
r\n\tat
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:4
82)\r\n\tat
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115)\r\n\
tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)\r\
n\tat
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\r\
n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344)\
r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391)\
r\n\tat
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)\r\
n\tat
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:
896)\r\n\tat
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744)
\r\n\tat
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)\r\
n\tat
org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java
:1191)\r\n\tat
org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.jav
a:659)\r\n\tat
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:63)\
r\n\tat java.base/java.lang.Thread.run(Thread.java:833)\r\n",
"message": "/ by zero",
"path": "/flipkart/get/emi"
}
result : 1233
by default Spring Web Module , when an exception occured at runtime level, Spring
will send Response with Exception Object details to the client as a Response with
Status Code.
Spring Web Module provide a solution, when an exception occured at runtime level,
to handle those exceptions and converting those exceptions into a responsble
response fromat with meaningfull Status codes.
Spring FW, provide a concept called ExceptionHandlers
try{
// Logic : Index
}catch(Null..Exception ){
}catch(exception ex){
=================================
Http Headers:
=============
https://www.instagram.com/dilipsingh_1306/
https://www.instagram.com/dilipsingh_1306/
Pre Defined Headers
User Defined Headers
Content-Type : application/xml
Requirement:
Create A Rest Service, where cleint should send always their hostname as part of
Header.
XML Vs JSON
-----------:
Req :
name,
"email
password":
"contact":
"city" :
"gender" :
Response :
-> to support JSON, are we added/configired any thing in Spring Werb Module?
NO
-> to support JSON, are we added/configired any thinf in REST API impl/Logic level
either Request or Response Body?
NO
@GetMapping(path = "/user/{city}/{gender}")
public List<UserDetails> getUsersByCityAndGender(@PathVariable("city") String
cityName,
@PathVariable String gender) {
System.out.println("Fetching USer Infromation by Gender :" + gender + "
, city : " + cityName);
name
email
password
contact
city
gender
XML :
<user>
<name>Dilip</name>
<email>[email protected]</email>
<password>dili111</password>
<contact>7237237273</contact>
<city>HYD</city>
<gender>MALE</gender>
</user>
By Default XML Converters are not configured internally by spring Web Module.
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-
dataformat-xml -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
consumes : application/json
produces : application/json
-> Add Dependency of XMl data fromat Conveter jar file.
Assignemnt :
<users>
<user>
<name>Dilip</name>
<email>[email protected]</email>
<password>dili111</password>
<contact>7237237273</contact>
<city>HYD</city>
<gender>MALE</gender>
</user>
<user>
<name>Dilip</name>
<email>[email protected]</email>
<password>dili111</password>
<contact>7237237273</contact>
<city>HYD</city>
<gender>MALE</gender>
</user>
<user>
<name>Dilip</name>
<email>[email protected]</email>
<password>dili111</password>
<contact>7237237273</contact>
<city>HYD</city>
<gender>MALE</gender>
</user>
<user>
<name>Dilip</name>
<email>[email protected]</email>
<password>dili111</password>
<contact>7237237273</contact>
<city>HYD</city>
<gender>MALE</gender>
</user>
<user>
<name>Dilip</name>
<email>[email protected]</email>
<password>dili111</password>
<contact>7237237273</contact>
<city>HYD</city>
<gender>MALE</gender>
</user>
</users>
Assignments :
Consumer Application :
Producer Applicatipn :
URL : localhost:9999/flipkart/user/create
Method : POST
Body : Yes
JSOn
{
"name": "string",
"email": "string",
"password": "string",
"contact": 0,
"gender": "string",
"city": "string"
}
RestTemplate:
exchange(...)
This method will be used for initiating Request from current application to another
application.
calalin RETS service of other app
HttpEntity : HttpEntity is a class provided by Spring Web
Can also be used in Spring MVC, as a return value from a @Controller method:
@GetMapping("/handle")
public HttpEntity<String> handle() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue");
return new HttpEntity<>("Hello World", responseHeaders);
}
GET
https://countriesnow.space/api/v0.1/countries/positions
{
"name": "string",
"email": "string",
"password": "string",
"contact": 0,
"gender": "string",
"city": "string",
"address": {
"city": "string",
"area": "string",
"state": "string",
"pincode": 0
}
}
===========================
Class Address
"address": {
"city": "string",
"area": "string",
"state": "string",
"pincode": 0
}
UserDetails
"name": "string",
"email": "string",
"password": "string",
"contact": 0,
"gender": "string",
"city": "string",
Address address;
=====================================
[
{
"email": "string",
"name": "string",
"password": "string",
"contact": 0,
"gender": "string",
"city": "string"
}
======================================
PhoneDesc{
color
capacity
PhoneDetails{
id
name
PhoneDesc data;
}
List<PhoneDetails> data = exchnage(url, method, null, List.class).getBody()
Request Body :
POJO :
===============================
application.yml
/ application.yaml
properties :
syntax :
name = value
spring.datasource.url=aws-sit
spring.datasource.username=sit
spring.datasource.password=sit
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
application.yaml:
server:
port: 9999
servlet:
context-path: /flipkart
spring:
datasource:
url:jdbc:oracle:thin:@localhost:1521:orcl
username: c##dilip
password: dilip
jpa:
hibernate:
ddl-auto: none
show-sql: true
Loggers
->
APR 11 10-10.30
122345 : Apr 11 :
Logging Frameworks:
Log4J
Slf4J
etcc.
#The java classes comes under package are effected with below log lvel.
logging.level.org.springframework=debug
logging.level.com.dilip.spring.boot.rest.api=debug
==================================================
================
Log Levels :
INFO
WARN
ERROR
TRACE
DEBUG
ERROR :
INFO
TRACE>DEBUG>INFO>WARN>ERROR
Agile Methodology
DEV :
SIT :
UAT :
prod :
-> syntax :
application-<env>.properties / application-<env>.yaml
-> Configure properties which are going change values from one env to another
env,
specific profile properties file.
-Dspring.profiles.active=uat
-> Spring Boot Actuator provides pre-defined endpoints which are related to
application
configurations and monitoring.
-> Spring Boot Actuator provided endpoints with starting with uri path /actuator
http://localhost:8888/flipkart/actuator/health
-> Actuator will enables by defualt only one endpoint /actuator/health out of many
endpoints.
->
http://localhost:8888/flipkart/actuator/beans
Student(1,"Dilip",25,35,99);
B
10, Properties
5 Required, 5 Optional
Student s1 = Student.builder()
.totalMarks(33)
.id(101)
.fee(2000)
.name("Dilip")
.email("[email protected]")
.build();
Spring Security:
===============
Security :
Security Breach :
https://www.flipkart.com/helpcentre?otracker=${otracker}_navlinks
Authentication
Authentication :
Authorization?
1. OAuth2
2. JWT (Java Web Tokens) : 90%
JWT :
=====
Token Creation
Login:
User ID : 8826111377
password : abcd12345
Validate Credentials
8826111377 +
+ Duration of Time :
24 Hours
Apr 26 8.45 Am
+jdjfjdkfsdjf
ad;sdbs;jdnbsdnsdnkl
Client
sadjsdhksdhka
<------------------------------
djasdb;ewtwh4worheor
Response
hdhsdhbsdkasdjsjdkaskbdajkdsjkdd
Body + Header
Client : 8826111377
ad;sdbs;jdnbsdnsdnkl
sadjsdhksdhka
djasdb;ewtwh4worheor
hdhsdhbsdkasdjsjdkaskbdajkdsjkdd
Decryption
ad;sdbs;jdnbsdnsdnkl
sadjsdhksdhka
djasdb;ewtwh4worheor
hdhsdhbsdkasdjsjdkaskbdajkdsjkdd
--
---
jdjfjdkfsdjf
--
Response
RefreshToken
Naresh
Login:
User ID : 1234567890
password : xyz123
Validate Credentials
1234567890 + jdjfjdkfsdjf
= JWT ->
ad;sdbdajs434r32423dnsjcns;jdnbsdnsdnkl
Client
saddfdjsd3rrw4hksdhka
<------------------------------
djasdb;ewsfddsdtwh4worheor
Response
hdhadeafe42543545sdhbsdkasdjsjdkaskbdajkdsjkdd
Body + Header
Hi
HEADER:
ALGORITHM & TOKEN TYPE
PAYLOAD:
DATA
SIGNATURE :
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI4ODI2MTExMzc3IiwiaWF0IjoxNTE2MjM5MD
IyfQ.77XBzSSNioUfRTjEbhYVtjh_WH9n7RBsMRBPUQQD5_E
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI5OTg5OTAwNDQwIiwiaWF0IjoxNTE2MjM5MD
IyfQ.ADwAKN5jfocd06cDalJqsPxx9qpbGBTQWiJjLMgsMcc
Authorizaation :
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI5OTg5OTAwNDQwIiwiaWF0IjoxNTE2MjM5MD
IyfQ.ADwAKN5jfocd06cDalJqsPxx9qpbGBTQWiJjLMgsMcc
eyJhbGciOiJIUzI1NiJ9.
eyJzdWIiOiJEaWxpcFNpbmdoIiwiaWF0IjoxNzE0MTg4NjkwLCJleHAiOjE3MTQxODg5OTB9.
9f60AEyfDfmeTCV_zcZmKssCkzoKeT2rTljWqgbcXrw
dilip123
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJkaWxpcDEyMyIsImlhdCI6MTcxNDM1NzMzNSwiZXhwIjoxNzE0Mz
U3NjM1fQ.AQAyMRVgDRHuXt8HWLhsWK42aaIfQrF4is0xVqmacNY
Today :
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJkaWxpcDEyMyIsImlhdCI6MTcxNDQ0Mzc5OSwiZXhwIjoxNzE0ND
Q0MDk5fQ.tB3AN5DagsM4pRO3u6luqa2QHsTc8rULUvFGfiLdT7Y
abcxyz
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhYmN4eXoiLCJpYXQiOjE3MTQzNTczNzEsImV4cCI6MTcxNDM1Nz
Y3MX0.ysTgw6zXZthhcEVWKjnhCrHuOc-SxjgwQfBuFhoak80
Today :
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhYmN4eXoiLCJpYXQiOjE3MTQ0NDM4MjYsImV4cCI6MTcxNDQ0ND
EyNn0.S1JsmyYvOd2Nsuq48VcN1f09M83O-Nhz9Jfu-YsdX24
4. Programming :
->
Security :
gmail :
login Id : gmail ID
password
flipkart :
login ID : Email Id / Mobile Number
insta:
login ID : Mobie / email / insta ID
jio savan :
Implementations are not used directly by Spring Security for security purposes.
They simply store user information which is later encapsulated into Authentication
objects. This allows non-security related user information (such as email
addresses,telephone numbers etc) to be stored in a convenient location.
Concrete implementations must take particular care to ensure the non-null contract
detailed for each method is enforced. See
org.springframework.security.core.userdetails.User for a referenceimplementation
(which you might like to extend or use in your code).
isAccountNonExpired : true
isAccountExpired : true
UserInforamtion
OncePerRequestFilter
Spring 6
-> SecurityFilterChain
Spring 5
WebSecurityConfigureAdapater
We will configure Rules like which api's should be authenticated , which api
should be ignored w.r.to authentication
Security :
GetSuresh1212122
foufhrpuhsd;oehgiwurgo72rwt97r79whn3
GetSuresh1212122
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJkaWxpcEBnbWFpbC5jb20iLCJpYXQiOjE3MTQ3OTI0OTIsImV4cC
I6MTcxNDc5Mjc5Mn0.8sN5i2XvFylqwzPSftDL4KtAGZU1PWTpU9U2Rn44HSE
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJkaWxpcEBnbWFpbC5jb20iLCJpYXQiOjE3MTQ3OTI2NzksImV4cC
I6MTcxNDc5Mjk3OX0.9lwSdoA2ThUoD9MoHi-4zUIumPECPnkSOZL-CXfm9jI
@dilipitacademy
1. ObjectMapper (dto,entiy)
2. MapStruct
MicroServices:
=============
Micro - Small
Services - applications
MonoLithic Application:
->
3 Micro Services
FE Team
User Reg :
user-service : 8001,8002,8003
API Gateway :
============
Steps :
=======
Gateway
Finsih
======
Routing Configuration:
====================
Request Routing:
#localhost:8888/user/register
===============
spring.application.name=flipkart-gateway
server.port=8888
logging.level.org.springframework=DEBUG
spring.cloud.gateway.mvc.routes[0].id=user-service
spring.cloud.gateway.mvc.routes[0].predicates[0]=Path=/user/**
spring.cloud.gateway.mvc.routes[0].uri = http://localhost:8001
spring.cloud.gateway.mvc.routes[1].id=order-service
spring.cloud.gateway.mvc.routes[1].predicates[0]=Path=/order/**
spring.cloud.gateway.mvc.routes[1].uri = http://localhost:8005
spring.cloud.gateway.mvc.routes[2].id=payment-service
spring.cloud.gateway.mvc.routes[2].predicates[0]=Path=/payment/**
spring.cloud.gateway.mvc.routes[2].uri = http://localhost:8010
============
localhost:8888/user/register
localhost:8888/order/create
localhost:8888/payment/netbanking/login
Student : Registering A Course : Java Full Stack : Admin Taken All Details
Service Registry :
=================
-> Service Registry Application will maintains all the Micro Services information,
which Micro Services are registred with Registry application.
Hostnames
port Numbers
Ip Address of MS
etcc..
Service Discovery :
Discovery CLient :
-> Finish
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka
localhost:8888/user/register
Syntax :
gatewayURI/Micro-Service-ID/REST-SERVICE_URI
localhost:8888/USER-SERVICE/user/register
localhost:8888/ORDER-SERVICE/order/create
localhost:8888/PAYMENT-SERVICE/payment/login
localhost:8888 : hostname :
aws-dev-silver.com/USER-SERVICE/user/register
localhost:8888/USER-SERVICE/user/register
localhost:8888/ORDER-SERVICE/order/create
localhost:8888/PAYMENT-SERVICE/payment/login
localhost:8888/user-service/***
localhost:8888/order-service/**
localhost:8888/payment-service/**
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=c##dilip
spring.datasource.password=dilip
Configuration :
Configuring Application :
Micro Service :
Common Properties
Private Properties
25 MS : [email protected]
5 MS : [email protected]
-> Create Config Serevr
-> Add
an annotation : @EnableConfigServer
-> Repo :
https://github.com/DilipItAcademy/flipkart-config-server.git
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
#[32m :: Spring Boot :: #[39m #[2m (v3.2.5)#[0;39m
Config CLient :
=============
spring.config.import=optional:configserver:http://localhost:9988/config
-> For example a property value is different from other micro services acording to
onmicro Service?
-> How to maintain a property accessed by specific to only That Micro Service?
dev
spring.datasource.url= aws-dev.com
uat
aws-uat.com
prod
aws-prod.com
-> Create Properties files specific to Env
application.properties
abc=123
application-dev.properties
spring.datasource.url= aws-dev.com
abc=111
application-uat.properties
spring.datasource.url= aws-uat.com
application-prod.properties
spring.datasource.url= aws-prod.com
spring.profiles.active=dev
abc = 111
application-dev.properties
spring.datasource.url= aws-dev.com
MS in DEV envi
user-service : dev
=================
application.properties
application-dev.properties
abc= 123
application-uat.properties
application-prod.properties
order-service.properties
payment-service.properties
user-service.properties
abc = 111
UC :
a MS is having it's own values specific to environment
user-service : dev
abc = 111
user-service : uat
abc = 222
user-service : prod
abc = 333
abc=123
application.properties
application-dev.properties
abc= 123
application-uat.properties
application-prod.properties
order-service.properties
payment-service.properties
user-service.properties
abc = 111
user-service-dev.properties
abc=111
user-service-uat.properties
abc=222
abc=111
abc=222
MicroServices Communication:
===========================
Request:
{
"name": "Naresh",
"email":
"[email protected]",
"contact":
"3233434342323",
"orderId":
"order1234",
"amount":88889
}
Response : String
8006
8009 :4
8077 : 3
8855 : 2
RestTemplate :
Feign Clients:
==============
Simliar to RestTemplate
8006
8009 :4
8077 : 3
8855 : 2
RestTemplate :
URL : <service-id>/order/create
order-service/order/create
order-service/order/cancel
/make/payment :
aws-pd.prod.com/***
OpenFeign
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
Circuit Breaker:
---------------