You are on page 1of 28

Spring Restfull:

1) Distributed Applications
2) Distributed Technologies
3) RestFull service Introduction
4) Rest Principles
5) XML
6) XSD
7) One time operation
8) Run Tine operation(a. Marshalling b. un-Marshalling)
9) JAX-B Introduction
10) JAX-B Architecture
11) Application development with JAX-B
12) JSON
13) XML VS JSON
14) JACKSON API
15) Converting Java object to JSON and Vice versa(JSON to java object)
16) GSON API
17) Converting java object to JSON and vice versa using GSON
18) HTTP Protocal Details
19) HTTP Methods(GET,POST,PUT,DELETE
20) HTTP Status codes
21) @RestController
22) @RequestBody
23) @ResponseBody
24) @RequestParam
25) @PathVariable
26) Media Types
27) Consumes(JSON data)
28) Produces(JSON Data)
29) Accept Header
30) Content-Type header
31) RestAPI Development Using Spring Boot
32) POSTMAN
33) SWAGGER & SWAGGER UI
34) Exception handling in Rest API
35) REST Security(JWT,OAuth2.0)
36) Mono Objects
37) Flux Objects
38) Rest Client Introduction
39) RestTemplate
40) WebClient
41) Synchronous and Astnchronous Calls
42) Apache Kafka in Spring Boot
43) Redis Cache Spring Boot

Micro Services:
1) Monolith Introduction
2) Monolith Architecture case study
3) Monolith Application Development Process
4) Load balancer(Cluster)case study
5) Load Balancing Algoritham(a.Round Robin, b)IP Hashing, c)Sticky Session)
6) Monolith Drawbacks
7) Micro Services Introduction
8) Micro Services Advantages
9) Micro Services Dis-Advantages
10) Micro Services Case study
11) Micro Services Architecture
12) Micro Services Development(a.API-1, b.API-2)
13) Inter service communication case study
14) Feign Client
15) Cloud Introduction.(AWS,AZURE,PCF)
16) PCF CLI Installation
17) Deploying Micro Services to PCF using CLI
18) Auto Scalling
19) Service Registry case study(Netflix Edurekha)
20) Gateway API(Zuul Proxy)
21) Hystrix(Circuit Breaker)
22) Hystrix Dashboard
23) Spring Boot Admin services.
RESTful Web Services Tutorial
RESTful Web Services are client and server applications that communicate over the WWW. RESTful Web
Services are REST Architecture based Web Services. In REST Architecture, everything is a resource. RESTful
Web Services provides communication between software applications running on different platforms and
frameworks. We can consider web services as code on demand. A RESTful Web Service is a function or
method which can be called by sending an HTTP request to a URL, and the service returns the result as the
response. In this tutorial, you will learn the basics of RSETful Web Services with suitable examples and
projects.

What is Web Services?


Web services are the types of internet software that uses standardized messaging protocol over the
distributed environment. It integrates the web-based application using the REST, SOAP,
WSDL, and UDDI over the network. For example, Java web service can communicate with .Net application.

Features of web Services


o Web services are designed for application to application interaction.

o It should be interoperable.

o It should allow communication over the network.

Components of Web Services


The web services must be able to fulfill the following conditions:

o The web service must be accessible over the internet.

o The web service is discoverable through a common mechanism like UDDI.

o It must be interoperable over any programming language or Operating System.

Uses of Web Services


o Web services are used for reusing the code and connecting the existing program.

o Web services can be used to link data between two different platforms.

o It provides interoperability between disparate applications.

How does data exchange between applications?


Suppose, we have an Application A which create a request to access the web services. The web services offer
a list of services. The web service process the request and sends the response to the Application A. The input
to a web service is called a request, and the output from a web service is called response. The web services
can be called from different platforms.

There are two popular formats for request and response XML and JSON.

XML Format: XML is the popular form as request and response in web services. Consider the following XML
code:

1. <getDetail>  
2. <id>DataStructureCourse</id>  
3. </getDetail>  

The code shows that user has requested to access the DataStrutureCourse. The other data exchange format
is JSON. JSON is supported by wide variety of platform.

JSON Format: JSON is a readable format for structuring data. It is used for transiting data between server and
web application.

1. [    
2.     "employee":   
3.    {    
4.         "id": 00987  
5.         "name":       "Jack",     
6.         "salary":      20000,     
7.    }    
8. ]    

To make a web service platform-independent, we make the request and response platform-independent.

Now a question arises, how does the Application A know the format of Request and Response?
The answer to this question is "Service Definition." Every web service offers a service definition. Service
definition specifies the following:

o Request/ Response format: Defines the request format made by consumer and response format
made by web service.

o Request Structure: Defines the structure of the request made by the application.

o Response Structure: Defines the structure of response returned by the web service.

o Endpoint: Defines where the services are available.

Key Terminology of Web Services

o Request and Response

o Message Exchange Format: XML and JSON

o Service Provider or Server

o Service Consumer or Client

o Service Definition

o Transport: HTTP and MQ

Request and Response: Request is the input to a web service, and the response is the output from a web
service.

Message Exchange Format: It is the format of the request and response. There are two popular message
exchange formats: XML and JSON.

Service Provider or Server: Service provider is one which hosts the web service.

Service Consumer or Client: Service consumer is one who is using the web service.

Service Definition: Service definition is the contract between the service provider and service consumer.
Service definition defines the format of request and response, request structure, response structure, and
endpoint.

Transport: Transport defines how a service is called. There is two popular way of calling a service: HTTP and
Message Queue (MQ). By tying the URL of service, we can call the service over the internet. MQ
communicates over the queue. The service requester puts the request in the queue. As soon as the service
provider listens to the request. It takes the request, process the request, and create a response, and put the
response back into MQ. The service requester gets the response from the queue. The communication
happens over the queue.
Characteristics of Web Services
Web services have the following characteristics:

o XML-based
o Coarse-grained
o Loosely coupled
o Capability to be synchronous and asynchronous
o Supports RPC

XML-based
A web service uses XML at information representation and record transportation layer. Using XML, there is
no need of networking, operating system, or platform binding. Web offering based application is highly
interoperable application at their middle level.

Coarse-grained
In the coarse-grained operation, a few objects hold a lot of related data. It provides broader functionality in
comparison to fine-grained service. It wraps one or more fine-grained services together into a coarse-grained
service. It is fine to have more coarse-grained service operations.

Loosely Coupled
A web service supports loosely coupled connections between systems. It communicates by passing XML
message to each other via a web API. Web API adds a layer of abstraction to the environment that makes the
connection adaptable and flexible.
Capability to be synchronous and asynchronous
Synchronous Web services are invoked over existing Web protocols by a client who waits for a response.
Synchronous Web services are served by RPC-oriented messaging.

Asynchronous Web services are invoked over existing Web protocols by a client who does not wait for a
response. The document-oriented messaging often used for asynchronous Web services. Asynchronous Web
Service is a crucial factor in enabling loosely coupled system.

Servlets, HTTP, and XML/SOAP are used to implement synchronous or asynchronous endpoints.

Supports RPC
A web service supports RPC through offering services of its personal, equivalent to those of a traditional
aspect.

o A web service is a web resource. We can access a web service using platform-independent and
language-neutral web protocols, such as HTTP. HTTP ensures easy integration of heterogeneous
environment.
o A web service is typically registered. It can be located through a web service registry. A registry
enables service consumers to find service that matches their needs. The service consumers may be
human or other application.
o A web service provides an interface (a web API) that can be called from another program. The
application-to-application programming can be invoked from any application.

Architecture of Web Services


The Web Services architecture describes how to instantiate the elements and implement the operations in an
interoperable manner.

The architecture of web service interacts among three roles: service provider, service requester, and service
registry. The interaction involves the three operations: publish, find, and bind. These operations and roles
act upon the web services artifacts. The web service artifacts are the web service software module and its
description.

The service provider hosts a network-associable module (web service). It defines a service description for the
web service and publishes it to a service requestor or service registry. These service requestor uses a find
operation to retrieve the service description locally or from the service registry. It uses the service description
to bind with the service provider and invoke with the web service implementation.

The following figure illustrates the operations, roles, and their interaction.
Roles in a Web Service Architecture
There are three roles in web service architecture:

o Service Provider

o Service Requestor

o Service Registry

Service Provider

From an architectural perspective, it is the platform that hosts the services.

Service Requestor

Service requestor is the application that is looking for and invoking or initiating an interaction with a service.
The browser plays the requester role, driven by a consumer or a program without a user interface.

Service Registry

Service requestors find service and obtain binding information for services during development.

Operations in a Web Service Architecture


Three behaviors that take place in the microservices:

o Publication of service descriptions (Publish)


o Finding of services descriptions (Find)

o Invoking of service based on service descriptions (Bind)

Publish: In the publish operation, a service description must be published so that a service requester can find
the service.

Find: In the find operation, the service requestor retrieves the service description directly. It can be involved
in two different lifecycle phases for the service requestor:

o At design, time to retrieve the service's interface description for program development.

o And, at the runtime to retrieve the service's binding and location description for invocation.

Bind: In the bind operation, the service requestor invokes or initiates an interaction with the service at
runtime using the binding details in the service description to locate, contact, and invoke the service.

Artifacts of the web service


There are two artifacts of web services:

o Service

o Service Registry

Service: A service is an interface described by a service description. The service description is the


implementation of the service. A service is a software module deployed on network-accessible platforms
provided by the service provider. It interacts with a service requestor. Sometimes it also functions as a
requestor, using other Web Services in its implementation.

Service Description: The service description comprises the details of the interface and implementation of


the service. It includes its data types, operations, binding information, and network location. It can also
categorize other metadata to enable discovery and utilize by service requestors. It can be published to a
service requestor or a service registry.

Web Service Implementation Lifecycle


A web service implementation lifecycle refers to the phases for developing web services from the
requirement to development. An Implementation lifecycle includes the following phases:

o Requirements Phase

o Analysis Phase

o Design Phase

o Coding Phase
o Test Phase

o Deployment Phase

Requirements Phase

The objective of the requirements phase is to understand the business requirement and translate them into
the web services requirement. The requirement analyst should do requirement elicitation (it is the practice of
researching and discovering the requirements of the system from the user, customer, and other
stakeholders). The analyst should interpret, consolidate, and communicate these requirements to the
development team. The requirements should be grouped in a centralized repository where they can be
viewed, prioritized, and mined for interactive features.

Analysis Phase

The purpose of the analysis phase is to refine and translate the web service into conceptual models by which
the technical development team can understand. It also defines the high-level structure and identifies the
web service interface contracts.

Design Phase

In this phase, the detailed design of web services is done. The designers define web service interface contract
that has been identified in the analysis phase. The defined web service interface contract identifies the
elements and the corresponding data types as well as mode of interaction between web services and client.
Coding Phase

Coding and debugging phase is quite similar to other software component-based coding and debugging
phase. The main difference lies in the creation of additional web service interface wrappers, generation of
WSDL, and client stubs.

Test Phase

In this phase, the tester performs interoperability testing between the platform and the client's program.
Testing to be conducted is to ensure that web services can bear the maximum load and stress. Other tasks
like profiling of the web service application and inspection of the SOAP message should also perform in the
test phase.

Deployment Phase

The purpose of the deployment phase is to ensure that the web service is properly deployed in the
distributed system. It executes after the testing phase. The primary task of deployer is to ensure that the web
service has been properly configured and managed. Other optional tasks like specifying and registering the
web service with a UDDI registry also done in this phase.

Web Service Stack or Web Service Protocol Stack


To perform three operations: publish, find, and bind in an interoperable manner, there must be a web
service stack. The web service stack embraces the standard at each level.
In the above figure, the top most layers build upon the capabilities provided by the lower layers. The three
vertical towers represent the requirements that are applied at every level of the stack. The text on the right
represents technologies that apply at that layer of the stack. A web service protocol stack typically stacks four
protocols:

o Transport Protocol

o Messaging Protocol

o Description Protocol

o Discovery Protocol

(Service) Transport Protocol: The network layer is the foundation of the web service stack. It is responsible
for transporting a message between network applications. HTTP is the network protocol for internet available
web services. It also supports other network protocol such as SMTP, FTP, and BEEP (Block Extensible
Exchange Protocol).

(XML) Messaging Protocol: It is responsible for encoding message in a common XML format so that they can
understand at either end of a network connection. SOAP is the chosen XML messaging protocol because it
supports three operations: publish, find, and bind operation.

(Service) Description Protocol: It is used for describing the public interface to a specific web service. WSDL is
the standard for XML-based service description. WSDL describes the interface and mechanics of service
interaction. The description is necessary to specify the business context, quality of service, and service-to-
service relationship.

(Service) Discovery Protocol: It is a centralized service into a common registry so that network Web services
can publish their location and description. It makes it easy to discover which services are available on the
network.

The first three layers of the stack are required to provide or use any web service. The simplest stack consists
of HTTP for the network layer, SOAP protocol for the XML-based messaging, and WSDL for the service
description layer. These three-layer provides interoperability and enables web service to control the existing
internet infrastructure. It creates a low cost of entry to a global environment.

The bottom three layers of the stack identify technologies for compliance and interoperability, the next two
layer- Service Publication and Service Discovery can be implemented with a range of solutions.

Types of Web Services


There are two types of web services:

o RESTful Web Servies


o SOAP Web Services
RESTful Web Services
REST stands for REpresentational State Transfer. It is developed by Roy Thomas Fielding who also developed
HTTP. The main goal of RESTful web services is to make web services more effective. RESTful web services try
to define services using the different concepts that are already present in HTTP. REST is an architectural
approach, not a protocol.

It does not define the standard message exchange format. We can build REST services with both XML and
JSON. JSON is more popular format with REST. The key abstraction is a resource in REST. A resource can be
anything. It can be accessed through a Uniform Resource Identifier (URI). For example:

The resource has representations like XML, HTML, and JSON. The current state is captured by
representational resource. When we request a resource, we provide the representation of the resource. The
important methods of HTTP are:

o GET: It reads a resource.


o PUT: It updates an existing resource.
o POST: It creates a new resource.
o DELETE: It deletes the resource.

For example, if we want to perform the following actions in the social media application, we get the
corresponding results.

POST /users: It creates a user.

GET /users/{id}: It retrieve the detail of one user.

GET /users: It retrieve the detail of all users.

DELETE /users: It delete all users.

DELETE /users/{id}: It delete a user.

GET /users/{id}/posts/post_id: It retrieve the detail of a specific post.

POST / users/{id}/ posts: It creates a post for a user.

GET /users/{id}/post: Retrieve all posts for a user

HTTP also defines the following standard status code:

o 404: RESOURCE NOT FOUND


o 200: SUCCESS
o 201: CREATED
o 401: UNAUTHORIZED
o 500: SERVER ERROR
RESTful Service Constraints
o There must be a service producer and service consumer.
o The service is stateless.
o The service result must be cacheable.
o The interface is uniform and exposing resources.
o The service should assume a layered architecture.

Advantages of RESTful web services


o RESTful web services are platform-independent.
o It can be written in any programming language and can be executed on any platform.
o It provides different data format like JSON, text, HTML, and XML.
o It is fast in comparison to SOAP because there is no strict specification like SOAP.
o These are reusable.
o These are language neutral.

SOAP Web Services


REST defines an architectural approach whereas SOAP poses a restriction on the format of the XML. XML
transfer data between the service provider and service consumer. Remember that SOAP and REST are
not comparable.

SOAP: SOAP acronym for Simple Object Access Protocol. It defines the standard XML format. It also defines
the way of building web services. We use Web Service Definition Language (WSDL) to define the format
of request XML and the response XML.

For example, we have requested to access the Todo application from the Facebook application. The


Facebook application sends an XML request to the Todo application. Todo application processes the request
and generates the XML response and sends back to the Facebook application.

If we are using SOAP web services, we have to use the structure of SOAP.


In the above figure, the SOAP-Envelope contains a SOAP-Header and SOAP-Body. It contains meta-
information needed to identify the request, for example, authentication, authorization, signature, etc. SOAP-
Header is optional. The SOAP-Body contains the real XML content of request or response. In case of an error,
the response server responds back with SOAP-Fault.

Let's understand the SOAP XML request and response structure.

XML Request

1. <Envelop xmlns=?http://schemas.xmlsoap.org/soap/envelop/?>  
2.     <Body>  
3.         <getCourseDetailRequest xmlns=?http://udemy.com/course?>  
4.             <id>course1</id>  
5.         <getCourseDetailRequest>  
6.     </Body>  
7. </Envelop>  

XML Response

1. <SOAP-ENV:Envelope xmlns:SOAP-ENV=?http://schemas.xmlsoap.org/soap/envelope/?>  
2.           <SOAP-ENV:Header />             <!?empty header-->  
3.            <SOAP-ENV:Body>                <!?body begin-->  
4.                   <ns2:getCourseDetailsResponse xmlns:ns2=?http://in28mi> <!--content of the response-->  
5.                    <ns2:course>  
6.                     <ns2:id>Course1</ns2:id>  
7.                     <ns2:name>Spring<ns2:name>  
8.                     <ns2:description>10 Steps</ns1:description>  
9.                     </ns2:course>  
10.                     </ns2:getCourseDetailResponse>  
11.                </SOAP-ENV:Body>       <!?body end-->  
12. </SOAP-ENV:Envelope>  

Points to remember
o SOAP defines the format of request and response.
o SOAP does not pose any restriction on transport. We can either use HTTP or MQ for communication.
o In SOAP, service definition typically done using Web Service Definition Language (WSDL). WSDL
defines Endpoint, All Operations, Request Structure, and Response Structure.

The Endpoint is the connection point where HTML or ASP pages are exposed. It provides the information
needed to address the Web Service endpoint. The operations are the services that are allowed to access.
Request structure defines the structure of the request, and the response structure defines the structure of
the response.

Web Services Components


There are two components of web services:

o Web Service Description Language (WSDL)

o Universal Description Discovery and Integration (UDDI)

Web Service Description Language (WSDL)


WSDL acronym for Web Service Description Language. WSDL is an XML based interface description language.
It is used for describing the functionality offered by a web service. Sometimes it is also known as the WSDL
file. The extension of the WSDL file is .wsdl. It provides the machine-readable description of how the service
can be called, what parameter it expects, and what data structure it returns.

It describes service as a collection of network endpoint, or ports. It is often used in combination with SOAP
and an XML schema to provide XML service over the distributed environment. In short, the purpose of WSDL
is similar to type-signature in a programming language.

The current version of WSDL is 2.0. Version 1.1 does not endorse by W3C.

Elements of WSDL
WSDL 1.1 WSDL Description
Term 2.0
Term

Service Service It is a set of system functions.

Port Endpoin It is an endpoint that defines a combination of binding and network addresses.
t

Binding Binding It specifies the interface and defines the SOAP binding style. It also defines the operations.

PortType Interfac An abstract set of services supported by one or more endpoints.


e

Operation Operati Abstract detail of an action supported by the service. It defines the SOAP actions and the way of encodi
on

Message N/A An abstract, typed definition of data to communicate. W3C has removed the message in WSDL 2.0, in w
bodies of inputs, outputs, and faults are referred directly.

Types Types It is a container for data type definition. The XML Schema language (XSD) is used for this purpose.
Universal Description, Discovery, and Integration (UDDI)
UDDI acronym for Universal Description, Discovery, and Integration. It is an XML-based registry for
businesses word wide to list themselves on the internet. It defines a set of services supporting the description
and discovery of the business, organizations, or other web service providers. The UDDI makes the services
available and the technical interfaces which may be used to access those services.

The idea behind UDDI is to discover organizations and the services that organizations offer, much like using a
telephone directory. It allows the business to list themselves by name, product, location, or the web
service they offer. A UDDI works in the following manner:

o A service provider registers its business with the UDDI registry.

o A service provider registers each service separately with the UDDI registry.

o The consumer looks up the business and service in the UDDI registry.

o The consumer binds the service with the service provider and uses the service.

The UDDI business registry system has three directories are as follows:
o White Pages

o Yellow pages

o Green Pages

White Pages: The white pages contain basic information such as company name, address, phone
number, and other business identifiers such as tax numbers.

Yellow Pages: The yellow pages contain detailed business data organized by relevant business classification.
The version of the yellow page classifies business according to the newer NAICS (North American Industry
Classification System).

Green Pages: The green pages contain information about the company's crucial business process, such
as operating platform, supported programs, and other high-level business protocols.

Difference between SOAP and RESTful Web Services

SOAP Protocol RESTful Web Services

SOAP is a protocol. REST is an architectural approach.

SOAP acronym for Simple Object Access Protocol. REST acronym for REpresentational State Transfer.

In SOAP, the data exchange format is always XML. There is no strict data exchange format. We can use JSON, XML, etc.

XML is the most popular data exchange format in SOAP JSON is the most popular data exchange format in RESTful web services.
web services.

SOAP uses Web Service Definition Language (WSDL). REST does not have any standard definition language.

SOAP does not pose any restrictions on transport. We can RESTful services use the most popular HTTP protocol.
use either HTTP or MQ.

SOAP web services are typical to implement. RESTful services are easier to implement than SOAP.

SOAP web services use the JAX-WS API. RESTful web services use the JAX-RS API.

SOAP protocol defines too many standards. RESTful services do not emphasis on too many standards.

SOAP cannot use RESTful services because it is a protocol. RESTful service can use SOAP web services because it is an architectural
approach that can use any protocol like HTTP and SOAP.

SOAP reads cannot be cached. REST reads can be cached.

Spring and JAXB Integration Example

1. Spring and JAXB Integration


2. Example of Spring and JAXB Integration

JAXB is an acronym for Java Architecture for XML Binding. It allows java developers to map Java class to XML
representation. JAXB can be used to marshal java objects into XML and vice-versa.

It is an OXM (Object XML Mapping) or O/M framework provided by Sun.

Advantage of JAXB
No need to create or use a SAX or DOM parser and write callback methods.

Example of Spring and JAXB Integration (Marshalling Java Object


into XML)
You need to create following files for marshalling java object into XML using Spring with JAXB:

1. Employee.java

2. applicationContext.xml

3. Client.java

Required Jar files

To run this example, you need to load:

o Spring Core jar files

o Spring Web jar files

download all the jar files for spring including core, web, aop, mvc, j2ee, remoting, oxm, jdbc, orm etc.
Employee.java

If defines three properties id, name and salary. We have used following annotations in this class:

1. @XmlRootElement It specifies the root element for the xml file.

2. @XmlAttribute It specifies attribute for the property.

3. @XmlElement It specifies the element.

1. package com.javatpoint;  
2. import javax.xml.bind.annotation.XmlAttribute;  
3. import javax.xml.bind.annotation.XmlElement;  
4. import javax.xml.bind.annotation.XmlRootElement;  
5.   
6. @XmlRootElement(name="employee")  
7. public class Employee {  
8. private int id;  
9. private String name;  
10. private float salary;  
11.   
12. @XmlAttribute(name="id")  
13. public int getId() {  
14.     return id;  
15. }  
16. public void setId(int id) {  
17.     this.id = id;  
18. }  
19. @XmlElement(name="name")  
20. public String getName() {  
21.     return name;  
22. }  
23. public void setName(String name) {  
24.     this.name = name;  
25. }  
26. @XmlElement(name="salary")  
27. public float getSalary() {  
28.     return salary;  
29. }  
30. public void setSalary(float salary) {  
31.     this.salary = salary;  
32. }  
33. }  

applicationContext.xml

It defines a bean jaxbMarshallerBean where Employee class is bound with the OXM framework.

1. <?xml version="1.0" encoding="UTF-8"?>  
2. <beans xmlns="http://www.springframework.org/schema/beans"  
3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
4.     xmlns:oxm="http://www.springframework.org/schema/oxm"  
5.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
6. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
7.         http://www.springframework.org/schema/oxm  
8.         http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">  
9.           
10.         <oxm:jaxb2-marshaller id="jaxbMarshallerBean">  
11.             <oxm:class-to-be-bound name="com.javatpoint.Employee"/>  
12.         </oxm:jaxb2-marshaller>  
13.   
14. </beans>  

Client.java

It gets the instance of Marshaller from the applicationContext.xml file and calls the marshal method.

1. package com.javatpoint;  
2. import java.io.FileWriter;  
3. import java.io.IOException;  
4. import javax.xml.transform.stream.StreamResult;  
5. import org.springframework.context.ApplicationContext;  
6. import org.springframework.context.support.ClassPathXmlApplicationContext;  
7. import org.springframework.oxm.Marshaller;  
8.   
9. public class Client{  
10.  public static void main(String[] args)throws IOException{  
11.   ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
12.   Marshaller marshaller = (Marshaller)context.getBean("jaxbMarshallerBean");  
13.           
14.   Employee employee=new Employee();  
15.   employee.setId(101);  
16.   employee.setName("Sonoo Jaiswal");  
17.   employee.setSalary(100000);  
18.           
19.   marshaller.marshal(employee, new StreamResult(new FileWriter("employee.xml")));  
20.     
21.   System.out.println("XML Created Sucessfully");  
22.  }  
23. }  

Output of the example


employee.xml

1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>  
2. <employee id="101">  
3. <name>Sonoo Jaiswal</name>  
4. <salary>100000.0</salary>  
5. </employee>  

JSON vs XML
A list of differences between JSON and XML are given below.

No JSON XML
.
1) JSON stands for JavaScript Object XML stands for eXtensible Markup Language.
Notation.

2) JSON is simple to read and write. XML is less simple than JSON.

3) JSON is easy to learn. XML is less easy than JSON.

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

5) JSON doesn't provide display XML provides the capability to display data because it is a markup language.
capabilities.

6) JSON supports array. XML doesn't support array.

7) JSON is less secured than XML. XML is more secured.

8) JSON files are more human XML files are less human readable.
readable than XML.

9) JSON supports only text and XML support many data types such as text, number, images, charts, graphs etc. Mor
number data type. transferring the format or structure of the data with actual data.

JSON Example
1. {"employees":[  
2.     {"name":"Vimal", "email":"vjaiswal1987@gmail.com"},  
3.     {"name":"Rahul", "email":"rahul12@gmail.com"},  
4.     {"name":"Jai", "email":"jai87@gmail.com"}  
5. ]}  

XML Example
1. <employees>  
2.     <employee>  
3.         <name>Vimal</name>   
4.         <email>vjaiswal1987@gmail.com</email>  
5.     </employee>  
6.     <employee>  
7.         <name>Rahul</name>   
8.         <email>rahul12@gmail.com</email>  
9.     </employee>  
10.     <employee>  
11.         <name>Jai</name>   
12.         <email>jai87@gmail.com</email>  
13.     </employee>  
14. </employees>  

Similarities between JSON and XML


o Both are simple and open.

o Both supports unicode. So internationalization is supported by JSON and XML both.

o Both represents self describing data.

o Both are interoperable or language-independent.

JACKSON API:
Jackson is a simple java based library to serialize java objects to JSON and vice versa.

Features
 Easy to use. - jackson API provides a high level facade to simplify commonly used use
cases.
 No need to create mapping. - jackson API provides default mapping for most of the
objects to be serialized.
 Performance. - jackson is quiet fast and is of low memory footprint and is suitable for
large object graphs or systems.
 Clean JSON. - jackson creates a clean and compact JSON results which is easy to read.
 No Dependency. - jackson library does not require any other library apart from jdk.
 Open Source - jackson library is open source and is free to use.
Three ways of processing JSON
Jackson provides three alternative ways to process JSON
 Streaming API - reads and writes JSON content as discrete events. JsonParser reads the
data whereas JsonGenerator writes the data. It is most powerful approach among the
three and is of lowest overhead and fastest in read/write opreations. It is Analogus to
Stax parser for XML.
 Tree Model - prepares a in-memory tree representation of the JSON document.
ObjectMapper build tree of JsonNode nodes. It is most flexible approach. It is analogus
to DOM parser for XML.
 Data Binding - converts JSON to and from POJO (Plain Old Java Object) using property
accessor or using annotations. It is of two type.
o Simple Data Binding - Converts JSON to and from Java Maps, Lists, Strings,
Numbers, Booleans and null objects.
o Full Data Binding - Converts JSON to and from any JAVA type.

ObjectMapper reads/writes JSON for both types of data bindings. Data Binding is most
convenient way and is analogus to JAXB parer for XML.

Converting Java object to JSON using Jackson api:

Example 1:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

Pojo class:
package com.madhu.Entity;

public class Employee {

private int eno;


private String ename;
private float esal;
private String eaddr;

public Employee(int eno, String ename, float esal, String eaddr) {


this.eno = eno;
this.ename = ename;
this.esal = esal;
this.eaddr = eaddr;
}
public int getEno() {
return eno;
}
public void setEno(int eno) {
this.eno = eno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public float getEsal() {
return esal;
}
public void setEsal(float esal) {
this.esal = esal;
}
public String getEaddr() {
return eaddr;
}
public void setEaddr(String eaddr) {
this.eaddr = eaddr;
}

package com.madhu.controller;

import java.util.ArrayList;

import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.madhu.Entity.Employee;

@RestController
public class Controller {

@GetMapping("/hello")
public String sayHello() {
return "Hello";
}

@GetMapping("/emp")
public List<Employee> getEmployeeDetails(){
ArrayList<Employee> arrayList = new ArrayList<>();
arrayList.add(new Employee(111, "madhu", 5000, "hyd"));
arrayList.add(new Employee(222, "ramesh", 6000, "hyd"));
return arrayList;
}
}

package com.madhu;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class App02Application {

public static void main(String[] args) {

SpringApplication.run(App02Application.class, args);

Rest Architecture:

You might also like