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

Chapter 4C REST wz Jackson

Chapter 4 Part III covers Spring concepts and REST APIs, focusing on the Spring Framework's architecture, including Inversion of Control (IoC) and Dependency Injection (DI). It explains the use of annotations for defining beans and their scopes, as well as the importance of the DispatcherServlet in Spring MVC for handling HTTP requests. Additionally, it discusses the creation of REST APIs using Spring, emphasizing practical applications and the integration of external services.

Uploaded by

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

Chapter 4C REST wz Jackson

Chapter 4 Part III covers Spring concepts and REST APIs, focusing on the Spring Framework's architecture, including Inversion of Control (IoC) and Dependency Injection (DI). It explains the use of annotations for defining beans and their scopes, as well as the importance of the DispatcherServlet in Spring MVC for handling HTTP requests. Additionally, it discusses the creation of REST APIs using Spring, emphasizing practical applications and the integration of external services.

Uploaded by

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

Chapter 4 Part III

Spring Concepts and REST APIs


Coverage
• Introduction to Spring
• Understanding the basic concepts of
the Spring Framework
• Working with the servlet dispatcher
• JSON Basics – Syntax and Data Binding
• REST HTTP Basics
• Spring REST
Understanding the patterns and paradigms of
Spring
➢Spring is a framework written in the Java language.
➢It provides lots of modules, such as Spring Data, Spring Security,
Spring Cloud, Spring Web, and so on.
➢It is popular for building enterprise applications.
➢Spring supports dependency injection (DI), also known as inversion of
control (IoC).
What is IoC?
• Inversion of Control (IoC) is a broader concept that DI is a part of. It means that
the control of the flow of a program is shifted from the program itself to a
framework or container.
• In the context of Spring, the IoC container manages the instantiation and wiring
of application components, effectively inverting the control of the component's
lifecycle from the developer to the container.
• Dependency Injection (DI) is a design pattern used in software development to
achieve loose coupling between different components of an application.
• In a DI/IoC container like Spring, instead of a component creating its
dependencies directly, the dependencies are provided (injected) from outside the
component. This allows for more flexible, maintainable, and testable code
because components are not tightly coupled to their dependencies.
DI is a type of IoC.

> IoC containers construct and maintain implementation objects.


> These types of objects (objects required by other objects – a form of
dependency) are injected into objects that need them in a
constructor, setter, or interface.
> This decouples the instantiation and allows DI at runtime.
> DI can also be achieved using the Service Locator pattern.
> However, we’ll stick to the IoC pattern approach.
What is AOP?
✓single-responsibility principle (SRP),
✓Abstract and encapsulate cross-cutting concerns.
✓Add aspects’ behavior around your code.
✓ Make the code for cross-cutting concerns modular to allow us to
easily maintain and extend it.
✓Focus on your business logic inside the code. This makes code clean.
Cross-cutting concerns are encapsulated and maintained separately
The application of IoC containers
• The Spring Framework’s backbone is the IoC container that is responsible for
a bean’s life cycle.
• In the Spring world, a Java object can be a bean if it is instantiated,
assembled, and managed by the IoC container.
• A bean may have dependencies that require other objects to work.
• The IoC container is responsible for injecting the object’s dependencies
when it creates that bean.
• In the Spring context, IoC is also known as DI.
• IoC container core is defined in two packages:
✓BeanFactory (org.springframework.beans.factory.BeanFactory) and
✓ApplicationContext (org.springframework.context.ApplicationContext) are two
important interfaces that provide the basis for IoC containers.
Defining a bean and its scope
• Beans are Java objects that are managed by the IoC containers.
• The developer supplies the configuration metadata to an IoC container, which
then uses the metadata to construct, assemble, and manage the beans.
• Each bean should have a unique identifier inside a container.
• A bean can even have more than one identity using an alias.
• @Bean annotation should be inside the @Component annotation.
• The @Component annotation is a generic way to declare a bean.
• A class annotated with @Configuration lets the method return a bean annotated
with @bean.
• @Configuration is meta-annotated with @ Component; therefore, the @Bean
annotation works inside it.
• There are other annotations such as @Controller, @Service, and @Repository,
which are also annotated with @Component.
The @ComponentScan annotation
• allows the auto-scanning of beans.
• It takes a few arguments, such as base packages and their classes. The Spring
container then investigates all the classes inside the base package and looks for
beans.
• It scans all classes annotated with @Component, or other annotations that are
meta-annotated with @Component, such as @Configuration, @Controller, and so
on.
• By default, Spring Boot takes the default base package from the class, which has
the @ComponentClass annotation. You can use the basePackageClasses attribute
to identify which packages should be scanned.
• Another way to scan more than two packages is by using the basePackages
attribute. It allows you to scan more than one package.
use more than one @ComponentScan
The bean’s scope
Singleton example
@Configuration
public class AppConfig { @Bean
// no scope is defined so default singleton @Scope(value =
// scope is applied. WebApplicationContext.SCOPE_REQUEST,
// If you want to define it explicitly, you can
// do that using
proxyMode = ScopedProxyMode.TARGET_CLASS)
// @Scope(value = // You need a proxyMode attribute because when
ConfigurableBeanFactory.SCOPE_SINGLETON) // web-aware context is instantiated
// OR
// @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
// Here,
// you don't have any HTTP request.
// ConfigurableBeanFactory.SCOPE_SINGLETON // Therefore, Spring injects the proxy as a
// is a string constant with value "singleton". // dependency and instantiates the bean when the
@Bean // HTTP request is invoked. OR, in short you
public SingletonBean singletonBean() {
return new SingletonBean();
// can simply write @RequestScope, a shortcut
} @RequestScope
@Bean public ReqScopedBean requestScopedBean() {
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) return new ReqScopedBean();
public PrototypeBean prototypeBean() {
return new PrototypeBean();
}
} }
@Configuration
public class AppConfig { web-aware context-related bean
@Bean
@Scope(value =
WebApplicationContext.SCOPE_REQUEST,
proxyMode = ScopedProxyMode.TARGET_CLASS) The @Import annotation
// You need a proxyMode attribute because when
// web-aware context is instantiated, you
// don't have any HTTP request. Therefore,
// Spring injects the proxy as a dependency and
• @Import is used for modularizing configurations
// instantiate the bean when HTTP request is when you have more than one configuration class.
// invoked. OR, in short you can annotate with • You can import the bean’s definitions from other
// @SessionScope, a shortcut for above configuration classes, and this is useful when you
@SessionScope
public ReqScopedBean requestScopedBean() { instantiate the context manually.
return new ReqScopedBean(); The @Import annotation • Spring Boot uses auto-configuration, so you don’t
} need to use @Import. However, you would have to
@ApplicationScope
public ReqScopedBean requestScopedBean() {
use @Import to modularize the configurations if you
return new ReqScopedBean(); want to instantiate the context manually
}
// here "scopeName" is alias for value
// interestingly, no shortcut. Also hard coded
// value for websocket
@Scope(scopeName = "websocket",
proxyMode = ScopedProxyMode.TARGET_CLASS)
public ReqScopedBean requestScopedBean() {
return new ReqScopedBean();
}
}
The @Import annotation example
The @DependsOn annotation
How to code DI
CartService has a dependency on CartRepository

The CartRepository instantiation is done


inside the CartService constructor:

We can decouple this dependency in the following way:

If you create a bean of the CartRepository


implementation, you can easily inject the
CartRepository bean using configuration
metadata
Using a setter method to define a
dependency
Using a constructor to
define a dependency public class CartService {
private CartRepository repository;
public void setCartRepository(CartRepository repository) {
this.repository = repository;
}
}
Now, you can use the following
configuration to inject the dependency:
@Configuration
public class AppConfig {
@Bean
public CartRepository cartRepository() {
return new CartRepositoryImpl();
}
@Bean
public CartService cartService() {
CartService service = new CartService();
Service.setCartService(cartRepository());
return service;
}
}
Using a class property to define a dependency

@Service e @Autowired annotation. It makes code look cleaner


public class CartService {
@Autowired
private CartRepository repository;
}

Configuring a bean’s metadata using annotations


How to use @Autowired?
• to define the configuration in a bean’s class itself, instead of writing a separate configuration class
annotated with @Configuration.
• can be applied to a field (as we saw in the class property-based DI example), constructor, setter, or any
method.
Example: @Autowired @Component
public class CartService {
private CartRepository repository;
private ARepository aRepository;
private BRepository bRepository;
private CRepository cRepository;
@Autowired // member(field) based auto wiring
private AnyBean anyBean;
@Autowired // constructor based autowired
public CartService(CartRepository repository) {
this.repository = repository;
}
@Autowired // Setter based auto wiring
public void setARepository(ARepository aRepo) {
this.aRepository = aRepo;
}
@Autowired // method based auto wiring
public void xMethod(BRepository bRepo, CRepository cRepo) {
this.bRepository = bRepo;
this.cRepository = cRepo;
}
}
Matching by type
• The code finds the
CartService bean and injects
it into CartController:
Matching by qualifier
• Let’s assume there is more than one bean of a
given type. As a result, the Spring container
won’t be able to determine the correct bean
by type matching:
Matching by name
What is the purpose of @Primary?
• The @Primary annotation allows
you to set one of the type’s beans as
the default.
• Bean annotation with @Primary will
be injected into auto-wired fields:
When can we use @Value?
Spring supports the use of external property files via .properties • The defaultCurrency field
or .yml. would take its value from the
default.currency field defined
in the application.properties
file.
• for Spring Boot, you don’t
need to use @ PropertySource.
• place application.yml or the
properties file under the
src/main/resources directory
Why use Spring Boot?
• Spring Boot has its own default configurations and also supports
auto-configuration to make productionready web application
development simple.
• Spring Initializr (http://start.spring.io) is a web-based service where
you simply choose your build tools, such as Maven or Gradle, along
with the project metadata, such as the group, artifacts, and any
dependencies.
• Once you fill in the required fields, you simply click on the Generate
Project button to be provided with a Spring Boot project that you can
use for your production application.
Understanding the importance of servlet
dispatcher
• Spring MVC is based on the Model-View-Controller (MVC) pattern
• Model: Models are Java objects (called POJOs) that contain the
application data. They also represent the state of the application.
• View: The view is a presentation layer that consists of
HTML/JSP/template files. The view renders the data from models and
generates the HTML output.
• Controller: The controller processes the user requests and builds the
model.
• DispatcherServlet is part of Spring MVC.
• it handles all the incoming HTTP requests.
The flow of an example user request in
Spring MVC for the REST controller:

Fig: DispatcherServlet
Questions

1. How do you define a bean with the prototype scope?


2. What is the difference between prototype and singleton beans?
3. What is required for a session and request scope to work?
4. What is the relationship between advice and pointcut in terms of AOP?
5. Write an Aspect for logging that prints the method and argument names
before the method execution, and prints a message with the return type (if
any) after the method’s successful execution.
Answers
1.By using the @Scope annotation as shown:
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
2. Beans defined using the singleton scope are instantiated only once per
Spring container. The same instance is injected every time it is requested,
whereas with a bean defined with the prototype scope, the container
creates a new instance every time the injection is done by the Spring
container for the requested bean. In short, a container creates a single
bean per container for a singleton-scoped bean, whereas a container
creates a new instance every time there is a new injection for prototype-
scoped beans.
3. Session and request scopes only work when a web-aware Spring context is
used. Other scopes that also need a web-aware context to work are
application and WebSocket scopes.
4. Advice is an action taken by the Aspect at a specific time (JoinPoint).
Aspects perform the additional logic (advice) at a certain point (JoinPoint),
such as a method being called, an exception being thrown, and so on.
Answer for qn 5
REST APIs - REST WebServices

m
You will learn how to …
• Create REST APIs / Web Services with Spring
You will learn how to …
• Create REST APIs / Web Services with Spring

• Discuss REST concepts, JSON and HTTP messaging


You will learn how to …
• Create REST APIs / Web Services with Spring

• Discuss REST concepts, JSON and HTTP messaging

• Install REST client tool: Postman


You will learn how to …
• Create REST APIs / Web Services with Spring

• Discuss REST concepts, JSON and HTTP messaging

• Install REST client tool: Postman

• Develop REST APIs / Web Services with @RestController


You will learn how to …
• Create REST APIs / Web Services with Spring

• Discuss REST concepts, JSON and HTTP messaging

• Install REST client tool: Postman

• Develop REST APIs / Web Services with @RestController

• Build a CRUD interface to the database with Spring REST


Practical Results
Practical Results

• Introduction to Spring REST development


Practical Results

• Introduction to Spring REST development

• Not an A to Z reference … for that you can see Spring Reference Manual
Practical Results

• Introduction to Spring REST development

• Not an A to Z reference … for that you can see Spring Reference Manual

https://projects.spring.io/spring-
framework/
Business Problem
Business Problem

• Build a client app that provides the weather report for a city
Business Problem

• Build a client app that provides the weather report for a city

• Need to get weather data from an external service


Application Architecture
Application Architecture

My
Weather
App
Application Architecture

My
Weather
App

App that we are


creating
(CLIENT)
Application Architecture

My Weather
Weather Service
App (external)

App that we are


creating
(CLIENT)
Application Architecture

My Weather
Weather Service
App (external)

App that we are Provided by


creating External
(CLIENT) Third Party
(SERVER)
Application Architecture

City
My Weather
Weather Service
App (external)

App that we are Provided by


creating External
(CLIENT) Third Party
(SERVER)
Application Architecture

City
My Weather
Weather Service
App (external)
Weather Report

App that we are Provided by


creating External
(CLIENT) Third Party
(SERVER)
Questions
Questions
• How will we connect to the Weather Service?
Questions
• How will we connect to the Weather Service?

• What programming language do we use?


Questions
• How will we connect to the Weather Service?

• What programming language do we use?

• What is the data format?


Answers
Answers
• How will we connect to the Weather Service?
Answers
• How will we connect to the Weather Service?

• We can make REST API calls over HTTP


Answers
• How will we connect to the Weather Service?

• We can make REST API calls over HTTP

• REST: REpresentational State Transfer


Answers
• How will we connect to the Weather Service?

• We can make REST API calls over HTTP

• REST: REpresentational State Transfer

• Lightweight approach for communicating between applications


Answers
Answers
• What programming language do we use?
Answers
• What programming language do we use?

• REST is language independent


Answers
• What programming language do we use?

• REST is language independent

• The client application can use ANY programming language


Answers
• What programming language do we use?

• REST is language independent

• The client application can use ANY programming language

• The server application can use ANY programming language


Answers
• What programming language do we use?

• REST is language independent

• The client application can use ANY programming language

• The server application can use ANY programming language

Java JavaScript
C# Go
Swift

PHP Ruby
Python
etc…
Answers
Answers
• What is the data format?
Answers
• What is the data format?

• REST applications can use any data format


Answers
• What is the data format?

• REST applications can use any data format

• Commonly see XML and JSON


Answers
• What is the data format?

• REST applications can use any data format

• Commonly see XML and JSON

• JSON is most popular and modern


Answers
• What is the data format?

• REST applications can use any data format

• Commonly see XML and JSON

• JSON is most popular and modern

• JavaScript Object Notation


Possible Solution
• Use free Weather Service provided by: openweathermap.org
Possible Solution
• Use free Weather Service provided by: openweathermap.org
Possible Solution
• Use free Weather Service provided by: openweathermap.org
Possible Solution
• Use free Weather Service provided by: openweathermap.org
Call Weather Service

• The API documentation gives us the following:

• Pass in the city name


Call Weather Service

• The API documentation gives us the following:

• Pass in the city name

api.openweathermap.org/data/2.5/weather?q={city name}

OR

api.openweathermap.org/data/2.5/weather?q={city name},{country code}


Response - WeatherReport

• The Weather Service responds with JSON


Response - WeatherReport

• The Weather Service responds with JSON

{
...
"temp": 14,
"temp_min": 11,
"temp_max": 17,
"humidity": 81,
"name": "London",
... Condensed
} version
Multiple Client Apps
Multiple Client Apps

Weather
Service
(external)
Multiple Client Apps

My
Weather

Spring MVC

Weather
Service
(external)
Multiple Client Apps

My
Weather

Spring MVC

My Weather
Weather Service
C# App
(external)
Multiple Client Apps

My
Weather

Spring MVC

My Weather
Weather Service
C# App
(external)

My
Weather

iPhone App
Multiple Client Apps Remember:

My
Weather

Spring MVC

My Weather
Weather Service
C# App
(external)

My
Weather

iPhone App
Multiple Client Apps Remember:
REST calls can be made over HTTP

My
Weather

Spring MVC

My Weather
Weather Service
C# App
(external)

My
Weather

iPhone App
Multiple Client Apps Remember:
REST calls can be made over HTTP
REST is language independent
My
Weather

Spring MVC

My Weather
Weather Service
C# App
(external)

My
Weather

iPhone App
Currency Converter App
Currency Converter App

My
Currency
App
Currency Converter App

My Currency
Currency Service
App (external)
Currency Converter App

USD to INR, 100.00


My Currency
Currency Service
App (external)
Currency Converter App

USD to INR, 100.00


My Currency
Currency Service
App (external)
6,478.52 INR
Currency Converter App

USD to INR, 100.00


My Currency
Currency Service
App (external)
6,478.52 INR

Of course this
fluctuates based
on the market
Movie TicketsApp
Movie Tickets App

My
Movie
App
Movie TicketsApp

My Movie Tickets
Movie Service
App (external)
Movie TicketsApp

Movie, Location, Time


My Movie Tickets
Movie Service
App (external)
Movie TicketsApp

Movie, Location, Time


My Movie Tickets
Movie Service
App (external)
Movie Results
Customer Relationship Manager (CRM) App
Customer Relationship Manager (CRM) App

CRM App
Customer Relationship Manager (CRM) App

CRM
CRM App Service
(spring-rest)
Customer Relationship Manager (CRM) App

Get customers
CRM
CRM App Service
(spring-rest)
Customer list
Customer Relationship Manager (CRM) App

Get customers
CRM
CRM App Service
(spring-rest)
Customer list

We will create
this code using
Spring REST
(SERVER)
Customer Relationship Manager (CRM) App

Get customers
CRM
CRM App Service
(spring-rest)
Customer list
Where to Find REST APIs

www.programmableweb.com
What do we call it?
What do we call it?

REST API

RESTful API
What do we call it?

REST
REST API
Web Services

RESTful
RESTful API
Web Services
What do we call it?

REST
REST API REST Services
Web Services

RESTful
RESTful API RESTful Services
Web Services
What do we call it?

REST
REST API REST Services
Web Services

RESTful
RESTful API RESTful Services
Web Services

Generally, all mean the SAME thing


What do we call it?

REST
REST API REST Services
Web Services

RESTful
RESTful API RESTful Services
Web Services

Generally, all mean the SAME thing


JSON Basics - Syntax

m
What is JSON?
What is JSON?

• JavaScript Object Notation


What is JSON?

• JavaScript Object Notation

• Lightweight data format for storing and exchanging data … plain text
What is JSON?

• JavaScript Object Notation

• Lightweight data format for storing and exchanging data … plain text

• Language independent … not just for JavaScript


What is JSON?

• JavaScript Object Notation

• Lightweight data format for storing and exchanging data … plain text

• Language independent … not just for JavaScript

• Can use with any programming language: Java, C#, Python etc …
What is JSON?

• JavaScript Object Notation

• Lightweight data format for storing and exchanging data … plain text

JSON is just
• Language independent … not just for JavaScript plain text
data

• Can use with any programming language: Java, C#, Python etc …
Simple JSON Example
Simple JSON Example

{
"id": 14,
"firstName": "Mario",
"lastName": "Rossi",
"active": true
}
Simple JSON Example

• Curley braces define objects in JSON

{
"id": 14,
"firstName": "Mario",
"lastName": "Rossi",
"active": true
}
Simple JSON Example

• Curley braces define objects in JSON

{
"id": 14,
• Object members are name / value pairs
"firstName": "Mario",
"lastName": "Rossi",
"active": true
}
Simple JSON Example

• Curley braces define objects in JSON

{
"id": 14,
• Object members are name / value pairs
"firstName": "Mario",
"lastName": "Rossi",
• Delimited by colons "active": true
}
Simple JSON Example
Name Value
• Curley braces define objects in JSON

{
"id": 14,
• Object members are name / value pairs
"firstName": "Mario",
"lastName": "Rossi",
• Delimited by colons "active": true
}
Simple JSON Example
Name Value
• Curley braces define objects in JSON

{
"id": 14,
• Object members are name / value pairs
"firstName": "Mario",
"lastName": "Rossi",
• Delimited by colons "active": true
}

• Name is always in double-quotes


JSON Values
JSON Values

{
"id": 14,
"firstName": "Mario",
"lastName": "Rossi",
"active": true,
"courses" : null
}
JSON Values
Value

{
"id": 14,
"firstName": "Mario",
"lastName": "Rossi",
"active": true,
"courses" : null
}
JSON Values
Value
• Numbers: no quotes
{
"id": 14,
"firstName": "Mario",
"lastName": "Rossi",
"active": true,
"courses" : null
}
JSON Values
Value
• Numbers: no quotes
{
• String: in double quotes "id": 14,
"firstName": "Mario",
"lastName": "Rossi",
"active": true,
"courses" : null
}
JSON Values
Value
• Numbers: no quotes
{
• String: in double quotes "id": 14,
"firstName": "Mario",
• Boolean: true, false "lastName": "Rossi",
"active": true,
"courses" : null
}
JSON Values
Value
• Numbers: no quotes
{
• String: in double quotes "id": 14,
"firstName": "Mario",
• Boolean: true, false "lastName": "Rossi",
"active": true,
• Nested JSON object "courses" : null
}
JSON Values
Value
• Numbers: no quotes
{
• String: in double quotes "id": 14,
"firstName": "Mario",
• Boolean: true, false "lastName": "Rossi",
"active": true,
• Nested JSON object "courses" : null
}
• Array
JSON Values
• Numbers: no Value
quotes

• String: in {
"id": 14,
double
"firstName": "Mario",
quotes "lastName": "Rossi",
"active": true,
• Boolean: "courses" : null
true, false }

• Nested JSON
object

• Array

• null
Nested JSON Objects
Nested JSON Objects

{
"id": 14,
"firstName": "Mario",
"lastName": "Rossi",
"active": true,
"address" : {
"street" : "100 Main St",
"city" : "Philadelphia",
"state" : "Pennsylvania",
"zip" : "19103",
"country" : "USA"
}
}
Nested JSON Objects

{
"id": 14,
"firstName": "Mario", Nested
"lastName": "Rossi",
"active": true,
"address" : {
"street" : "100 Main St",
"city" : "Philadelphia",
"state" : "Pennsylvania",
"zip" : "19103",
"country" : "USA"
}
}
JSON Arrays
JSON Arrays

{
"id": 14,
"firstName": "Mario",
"lastName": "Rossi",
"active": true,
"languages" : ["Java", "C#", "Python", "Javascript"]
}
JSON Arrays

{
"id": 14, Array
"firstName": "Mario",
"lastName": "Rossi",
"active": true,
"languages" : ["Java", "C#", "Python", "Javascript"]
}
Java JSON Data Binding

m
Java JSON Data Binding
Java JSON Data Binding

• Data binding is the process of converting JSON data to a Java POJO


Java JSON Data Binding

• Data binding is the process of converting JSON data to a Java POJO

JSON
Java JSON Data Binding

• Data binding is the process of converting JSON data to a Java POJO

Java
JSON
POJO
Java JSON Data Binding

• Data binding is the process of converting JSON data to a Java POJO

Java
JSON
POJO
Java JSON Data Binding

• Data binding is the process of converting JSON data to a Java POJO

Java
JSON
POJO
Java JSON Data Binding

• Data binding is the process of converting JSON data to a Java POJO

Java
JSON
POJO
Data Binding
Java JSON Data Binding

• Data binding is the process of converting JSON data to a Java POJO

Java
JSON
POJO Also known as
Mapping

Data Binding Serialization / Deserialization

Marshalling / Unmarshalling
JSON Data Binding with Jackson
JSON Data Binding with Jackson
• Spring uses the Jackson Project behind the scenes
JSON Data Binding with Jackson
• Spring uses the Jackson Project behind the scenes

• Jackson handles data binding between JSON and Java POJO


JSON Data Binding with Jackson
• Spring uses the Jackson Project behind the scenes

• Jackson handles data binding between JSON and Java POJO

• Details on Jackson Project:


JSON Data Binding with Jackson
• Spring uses the Jackson Project behind the scenes

• Jackson handles data binding between JSON and Java POJO

• Details on Jackson Project:

https://github.com/FasterXML/jackson-databind
Jackson Data Binding
Jackson Data Binding

• Jackson Data Binding API


Jackson Data Binding

• Jackson Data Binding API

• Package: com.fasterxml.jackson.databind
Jackson Data Binding

• Jackson Data Binding API

• Package: com.fasterxml.jackson.databind

• Maven Dependency

<dependency>
<groupId>com.fasterxml.jackson.core</groupId
>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
Jackson Data Binding
Jackson Data Binding

• By default, Jackson will call appropriate getter/setter method


Jackson Data Binding

• By default, Jackson will call appropriate getter/setter method

{
"id": 14,

"firstName": "Mario",

"lastName": "Rossi",

"active": true
}
Jackson Data Binding

• By default, Jackson will call appropriate getter/setter method

{
"id": 14,
Java
"firstName": "Mario", POJO
"lastName": "Rossi",

"active": true
}
Student
Jackson Data Binding

• By default, Jackson will call appropriate getter/setter method

{
"id": 14,
Java
"firstName": "Mario", POJO
"lastName": "Rossi",

"active": true
}
Student
Jackson Data Binding

• By default, Jackson will call appropriate getter/setter method

{
"id": 14,
Java
"firstName": "Mario", POJO
"lastName": "Rossi",

"active": true
}
Student
JSON to Java POJO
JSON to Java POJO

• Convert JSON to Java POJO … call setter methods on POJO


JSON to Java POJO

• Convert JSON to Java POJO … call setter methods on POJO

{
"id": 14,
Java
"firstName": "Mario", POJO
"lastName": "Rossi",

"active": true
}
Student
JSON to Java POJO

• Convert JSON to Java POJO … call setter methods on POJO

{ Call
"id": 14, setXXX Java
methods
"firstName": "Mario", POJO
"lastName": "Rossi",

"active": true
}
Student
JSON to Java POJO

• Convert JSON to Java POJO … call setter methods on POJO

{ Call
"id": 14, setXXX Java
methods
"firstName": "Mario", POJO
"lastName": "Rossi",

"active": true
} Jackson will do Student
this work
JSON to Java POJO
JSON to Java POJO

• Convert JSON to Java POJO … call setter methods on POJO


JSON to Java POJO

• Convert JSON to Java POJO … call setter methods on POJO

{
"id": 14,

"firstName": "Mario",

"lastName": "Rossi",

"active": true
}
JSON to Java POJO

• Convert JSON to Java POJO … call setter methods on POJO


public class Student {

private int id;


private String firstName;
private String lastName;

{ private boolean active;

"id": 14, public void setId(int id) {


this.id = id;
}

"firstName": "Mario", public void setFirstName(String firstName) {


this.firstName = firstName;
}

"lastName": "Rossi", public void setLastName(String lastName) {


this.lastName = lastName;
}

"active": true public void setActive(boolean active) {


this.active = active;
} }

// getter methods
}
JSON to Java POJO

• Convert JSON to Java POJO … call setter methods on POJO


public class Student {

private int id;


private String firstName;
private String lastName;

{ private boolean active;

"id": 14, Call setId(…) public void setId(int id) {


this.id = id;
}

"firstName": "Mario", public void setFirstName(String firstName) {


this.firstName = firstName;
}

"lastName": "Rossi", public void setLastName(String lastName) {


this.lastName = lastName;
}

"active": true public void setActive(boolean active) {


this.active = active;
} }

// getter methods
}
JSON to Java POJO

• Convert JSON to Java POJO … call setter methods on POJO


public class Student {

private int id;


private String firstName;
private String lastName;

{ private boolean active;

"id": 14, Call setId(…) public void setId(int id) {


this.id = id;
}

"firstName": "Mario", public void setFirstName(String firstName) {


this.firstName = firstName;
}

"lastName": "Rossi", public void setLastName(String lastName) {


this.lastName = lastName;
Jackson will do }

"active": true this work public void setActive(boolean active) {


this.active = active;
} }

// getter methods
}
JSON to Java POJO

• Convert JSON to Java POJO … call setter methods on POJO


public class Student {

private int id;


private String firstName;
private String lastName;

{ private boolean active;

"id": 14, Call setId(…) public void setId(int id) {


this.id = id;
}

"firstName": "Mario", Call setFirstName(…) public void setFirstName(String firstName) {


this.firstName = firstName;
}

"lastName": "Rossi", public void setLastName(String lastName) {


this.lastName = lastName;
}

"active": true public void setActive(boolean active) {


this.active = active;
} }

// getter methods
}
JSON to Java POJO

• Convert JSON to Java POJO … call setter methods on POJO


public class Student {

private int id;


private String firstName;
private String lastName;

{ private boolean active;

"id": 14, Call setId(…) public void setId(int id) {


this.id = id;
}

"firstName": "Mario", Call setFirstName(…) public void setFirstName(String firstName) {


this.firstName = firstName;
}

"lastName": "Rossi", Call setLastName(…) public void setLastName(String lastName) {


this.lastName = lastName;
}

"active": true public void setActive(boolean active) {


this.active = active;
} }

// getter methods
}
JSON to Java POJO

• Convert JSON to Java POJO … call setter methods on POJO


public class Student {

private int id;


private String firstName;
private String lastName;

{ private boolean active;

"id": 14, Call setId(…) public void setId(int id) {


this.id = id;
}

"firstName": "Mario", Call setFirstName(…) public void setFirstName(String firstName) {


this.firstName = firstName;
}

"lastName": "Rossi", Call setLastName(…) public void setLastName(String lastName) {


this.lastName = lastName;
}

"active": true Call setActive(…) public void setActive(boolean active) {


this.active = active;
} }

// getter methods
}
JSON to Java POJO Note: Jackson calls the setXXX methods
It does NOT access internal private fields directly

• Convert JSON to Java POJO … call setter methods on POJO


public class Student {

private int id;


private String firstName;
private String lastName;

{ private boolean active;

"id": 14, Call setId(…) public void setId(int id) {


this.id = id;
}

"firstName": "Mario", Call setFirstName(…) public void setFirstName(String firstName) {


this.firstName = firstName;
}

"lastName": "Rossi", Call setLastName(…) public void setLastName(String lastName) {


this.lastName = lastName;
}

"active": true Call setActive(…) public void setActive(boolean active) {


this.active = active;
} }

// getter methods
}
JSON to Java POJO
JSON to Java POJO
import java.io.File;

import com.fasterxml.jackson.databind.ObjectMapper;
JSON to Java POJO
import java.io.File;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Driver {

public static void main(String[] args) throws Exception {


JSON to Java POJO
import java.io.File;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Driver {

public static void main(String[] args) throws Exception {

// create object mapper


ObjectMapper mapper = new ObjectMapper();
JSON to Java POJO
import java.io.File;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Driver {

public static void main(String[] args) throws Exception {

// create object mapper


ObjectMapper mapper = new ObjectMapper();
JSON to Java POJO
import java.io.File;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Driver {

public static void main(String[] args) throws Exception {

// create object mapper


ObjectMapper mapper = new ObjectMapper();

// read JSON from file and map/convert to Java POJO


Student myStudent = mapper.readValue(new File("data/sample.json"), Student.class);
JSON to Java POJO
import java.io.File;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Driver {

public static void main(String[] args) throws Exception {

// create object mapper


ObjectMapper mapper = new ObjectMapper();

// read JSON from file and map/convert to Java POJO


Student myStudent = mapper.readValue(new File("data/sample.json"), Student.class);
JSON to Java POJO
import java.io.File;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Driver {

public static void main(String[] args) throws Exception {

// create object mapper


ObjectMapper mapper = new ObjectMapper();

// read JSON from file and map/convert to Java POJO


Student myStudent = mapper.readValue(new File("data/sample.json"), Student.class);
JSON to Java POJO
import java.io.File;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Driver {

public static void main(String[] args) throws Exception {

// create object mapper


ObjectMapper mapper = new ObjectMapper();

// read JSON from file and map/convert to Java POJO


Student myStudent = mapper.readValue(new File("data/sample.json"), Student.class);
JSON to Java POJO
import java.io.File;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Driver {

public static void main(String[] args) throws Exception {

// create object mapper


ObjectMapper mapper = new ObjectMapper();

// read JSON from file and map/convert to Java POJO


Student myStudent = mapper.readValue(new File("data/sample.json"), Student.class);

1. Read data from this file


JSON to Java POJO
import java.io.File;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Driver {

public static void main(String[] args) throws Exception {

// create object mapper


ObjectMapper mapper = new ObjectMapper();

// read JSON from file and map/convert to Java POJO


Student myStudent = mapper.readValue(new File("data/sample.json"), Student.class);

2. Create an instance of
1. Read data from this file this class and populate it
JSON to Java POJO
import java.io.File;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Driver {

public static void main(String[] args) throws Exception {

// create object mapper


ObjectMapper mapper = new ObjectMapper();

// read JSON from file and map/convert to Java POJO


Student myStudent = mapper.readValue(new File("data/sample.json"), Student.class);

// also print individual items


System.out.println("First name = " + myStudent.getFirstName());
System.out.println("Last name = " + myStudent.getLastName());

}
}
JSON to Java POJO
import java.io.File;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Driver {

public static void main(String[] args) throws Exception {

// create object mapper


ObjectMapper mapper = new ObjectMapper();

// read JSON from file and map/convert to Java POJO


Student myStudent = mapper.readValue(new File("data/sample.json"), Student.class);

// also print individual items Output


System.out.println("First name = " + myStudent.getFirstName());
System.out.println("Last name = " + myStudent.getLastName());
First name = Mario
Last name = Rossi
}
}
Java POJO to JSON
Java POJO to JSON
• Now, let’s go the other direction

• Convert Java POJO to JSON … call getter methods on POJO


Java POJO to JSON
• Now, let’s go the other direction

• Convert Java POJO to JSON … call getter methods on POJO

Java
POJO

Student
Java POJO to JSON
• Now, let’s go the other direction

• Convert Java POJO to JSON … call getter methods on POJO

Java
POJO

Student
Java POJO to JSON
• Now, let’s go the other direction

• Convert Java POJO to JSON … call getter methods on POJO

{
"id": 14,
Java
"firstName": "Mario", POJO
"lastName": "Rossi",

"active": true
}
Student
Java POJO to JSON
• Now, let’s go the other direction

• Convert Java POJO to JSON … call getter methods on POJO

{
"id": 14,
Java
"firstName": "Mario", POJO
"lastName": "Rossi", Call
getXXX
"active": true
}
methods Student
Java POJO to JSON
• Now, let’s go the other direction

• Convert Java POJO to JSON … call getter methods on POJO

{
"id": 14,
Java
"firstName": "Mario", POJO
"lastName": "Rossi", Call
getXXX
"active": true
}
methods Student
Jackson will do
this work
Java POJO to JSON
Java POJO to JSON
// create object mapper
ObjectMapper mapper = new ObjectMapper();

// read JSON from file and map/convert Java POJO


Student.class)
Student myStudent to File("data/sample.json"),
;
= mapper.readValue(new
...
Java POJO to JSON
// create object mapper
ObjectMapper mapper = new ObjectMapper();

// read JSON from file and map/convert Java POJO


Student.class)
Student myStudent to File("data/sample.json"),
;
= mapper.readValue(new
//
...now write JSON to output file
mapper.enable(SerializationFeature.INDENT_OUTPUT);
Java POJO to JSON
// create object mapper
ObjectMapper mapper = new ObjectMapper();

// read JSON from file and map/convert to Java POJO


Student myStudent = mapper.readValue(new File("data/sample.js o n" ) , S t u de nt . c la ss) ;
... I n d e n t t h e J S O N o utputfor
"pretty printing"
// now write JSON to output file
mapper.enable(SerializationFeature.INDENT_OUTPUT);
Java POJO to JSON
// create object mapper
ObjectMapper mapper = new ObjectMapper();

// read JSON from file and map/convert Java POJO


Student.class)
Student myStudent to File("data/sample.json"),
;
= mapper.readValue(new
//
...now write JSON to output file
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValue(new File("data/output.json"), myStudent);
Java POJO to JSON
// create object mapper
ObjectMapper mapper = new ObjectMapper();

// read JSON from file and map/convert Java POJO


Student.class)
Student myStudent to File("data/sample.json"),
;
= mapper.readValue(new
//
...now write JSON to output file
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValue(new File("data/output.json"), myStudent);

Jackson calls the getter methods on


Student POJO
to create JSON output file
Java POJO to JSON
// create object mapper
ObjectMapper mapper = new ObjectMapper();

// read JSON from file and map/convert Java POJO


Student.class)
Student myStudent to File("data/sample.json"),
;
= mapper.readValue(new
//
...now write JSON to output file
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValue(new File("data/output.json"), myStudent);

File: data/output.json
Jackson calls the getter methods on {
"id": 14,
Student POJO "firstName": "Mario",
"lastName": "Rossi",
to create JSON output file "active": true
}
Spring and Jackson Support
Spring and Jackson Support

• When building Spring REST applications


Spring and Jackson Support

• When building Spring REST applications

• Spring will automatically handle Jackson Integration


Spring and Jackson Support

• When building Spring REST applications

• Spring will automatically handle Jackson Integration

• JSON data being passed to REST controller is converted to POJO


Spring and Jackson Support

• When building Spring REST applications

• Spring will automatically handle Jackson Integration

• JSON data being passed to REST controller is converted to POJO

• Java object being returned from REST controller is converted to JSON


Spring and Jackson Support

• When building Spring REST applications


Happens
automatically
behind the scenes
• Spring will automatically handle Jackson Integration

• JSON data being passed to REST controller is converted to POJO

• Java object being returned from REST controller is converted to JSON


REST HTTP Basics

m
REST over HTTP
• Most common use of REST is over HTTP

• Leverage HTTP methods for CRUD operations


REST over HTTP
• Most common use of REST is over HTTP

• Leverage HTTP methods for CRUD operations

HTTP Method CRUD Operation


REST over HTTP
• Most common use of REST is over HTTP

• Leverage HTTP methods for CRUD operations

HTTP Method CRUD Operation


POST Create a new entity
REST over HTTP
• Most common use of REST is over HTTP

• Leverage HTTP methods for CRUD operations

HTTP Method CRUD Operation


POST Create a entity
new
GET Read a list of entities or single entity
REST over HTTP
• Most common use of REST is over HTTP

• Leverage HTTP methods for CRUD operations

HTTP Method CRUD


Operation
POST Create a new entity
GET Read a list of entities or single entity
PUT Update an existing entity
REST over HTTP
• Most common use of REST is over HTTP

• Leverage HTTP methods for CRUD operations

HTTP Method CRUD


Operation
POST Create a new entity
GET Read a list of entities or single entity
PUT Update an existing entity
DELETE Delete an existing entity
HTTP Messages
HTTP Messages

Client Server

My CRM
CRM REST
App Service
HTTP Messages

HTTP Request
Client Message Server

My CRM
CRM REST
App Service
HTTP Messages

HTTP Request
Client Message Server

My CRM
CRM REST
App Service

HTTP Response
Message
HTTP Request Message

HTTP Request Message

Request line

Header variables

Message body
HTTP Request Message

HTTP Request Message


• Request line: the HTTP command
Request line

Header variables

Message body
HTTP Request Message

HTTP Request Message


• Request line: the HTTP command
Request line

• Header variables: request metadata Header variables

Message body
HTTP Request Message

HTTP Request Message


• Request line: the HTTP command
Request line

• Header variables: request metadata Header variables

Message body
• Message body: contents of message
HTTP Response Message

HTTP Response Message

Response line

Header variables

Message body
HTTP Response Message

• Response line: server protocol and status code

HTTP Response Message

Response line

Header variables

Message body
HTTP Response Message

• Response line: server protocol and status code

HTTP Response Message


• Header variables: response metadata
Response line

Header variables

Message body
HTTP Response Message

• Response line: server protocol and status code

HTTP Response Message


• Header variables: response metadata
Response line

• Message body: contents of message Header variables

Message body
HTTP Response - Status Codes
HTTP Response - Status Codes

Code Range Description


HTTP Response - Status Codes

Code Range
De
scription
100 - 199 Informational
HTTP Response - Status Codes

Code Range
De
scription
100 - 199 Informational

200 - 299 Successful


HTTP Response - Status Codes

Code Range
De
scription
100 - 199 Informational

200 - 299 Successful

300 - 399 Redirection


HTTP Response - Status Codes

Code Range
De
scription
100 - 199 Informational

200 - 299 Successful

300 - 399 Redirection

400 - 499 Client error


HTTP Response - Status Codes

Code Range
De
scription
100 - 199 Informational

200 - 299 Successful

300 - 399 Redirection

400 - 499 Client error

500 - 599 Server error


HTTP Response - Status Codes

Code Range Description

100 - 199 Informational

200 - 299 Successful


401 Authentication Required
300 - 399 Redirection 404 File Not Found

400 - 499 Client error

500 - 599 Server error


HTTP Response - Status Codes

Code Range Description

100 - 199 Informational

200 - 299 Successful


401 Authentication Required
300 - 399 Redirection 404 File Not Found

400 - 499 Client error

500 - 599 Server error


500 Internal Server Error
MIME Content Types
MIME Content Types
• The message format is described by MIME content type
MIME Content Types
• The message format is described by MIME content type

• Multipurpose Internet Mail-Extension


MIME Content Types
• The message format is described by MIME content type

• Multipurpose Internet Mail-Extension

• Basic Syntax: type/sub-type


MIME Content Types
• The message format is described by MIME content type

• Multipurpose Internet Mail-Extension

• Basic Syntax: type/sub-type

• Examples
MIME Content Types
• The message format is described by MIME content type

• Multipurpose Internet Mail-Extension

• Basic Syntax: type/sub-type

• Examples

• text/html, text/plain
MIME Content Types
• The message format is described by MIME content type

• Multipurpose Internet Mail-Extension

• Basic Syntax: type/sub-type

• Examples

• text/html, text/plain

• application/json, application/xml, …
Client Tool
Client Tool

• We need a client tool


Client Tool

• We need a client tool


Client Tool

• We need a client tool

• Send HTTP requests to the REST Web Service / API


Client Tool

• We need a client tool

• Send HTTP requests to the REST Web Service / API


Client Tool

• We need a client tool

• Send HTTP requests to the REST Web Service / API

• Plenty of tools available: curl, Postman, etc …


Postman
Postman
Postman

www.getpostman.com
Postman

Free
developer
plan

www.getpostman.com
Install Postman Now
Install Postman Now

www.getpostman.com
Spring REST Controller

m
Spring REST Support
Spring REST Support
• Spring Web MVC provides support for Spring REST
Spring REST Support
• Spring Web MVC provides support for Spring REST

• New annotation @RestController


Spring REST Support
• Spring Web MVC provides support for Spring REST

• New annotation @RestController

• Extension of @Controller
Spring REST Support
• Spring Web MVC provides support for Spring REST

• New annotation @RestController

• Extension of @Controller

• Handles REST requests and responses


Spring REST Support
• Spring Web MVC provides support for Spring REST

• New annotation @RestController

• Extension of @Controller

• Handles REST requests and responses

• Spring REST will also automatically convert Java POJOs to JSON


Spring REST Support
• Spring Web MVC provides support for Spring REST

• New annotation @RestController

• Extension of @Controller

• Handles REST requests and responses

• Spring REST will also automatically convert Java POJOs to JSON

• As long as the Jackson project is on the classpath or pom.xml


Spring REST HelloWorld
Spring REST HelloWorld

REST
Client
Spring REST HelloWorld

REST REST
Client Service
Spring REST HelloWorld

/test/hello

REST REST
Client Service
Spring REST HelloWorld

/test/hello

REST REST
Client Service
Hello World!
Spring REST HelloWorld We will write
this code

/test/hello

REST REST
Client Service
Hello World!
Spring REST HelloWorld We will write
this code

/test/hello

REST REST
Client Service
Hello World!

Web Browser
Or
Postman
Spring REST Controller
Spring REST Controller

@RestController
@RequestMapping("/test")
public class DemoRestController {
Spring REST Controller
Adds REST support

@RestController
@RequestMapping("/test")
public class DemoRestController {
Spring REST Controller
Adds REST support

@RestController
@RequestMapping("/test")
public class DemoRestController {

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

}
Spring REST Controller
Adds REST support

@RestController
@RequestMapping("/test")
public class DemoRestController {
Access the REST endpoint at
@GetMapping("/hello")
/test/hello
public String sayHello() {
return "Hello World!";
}

}
Spring REST Controller
Adds REST support

@RestController
@RequestMapping("/test")
public class DemoRestController {
Access the REST endpoint at
@GetMapping("/hello")
/test/hello
public String sayHello() {
return "Hello World!";
}

}
Returns content to
client
Testing with REST Client - Postman
Testing with REST Client - Postman
Testing with REST Client - Postman
Access the REST endpoint at
/test/hello
Testing with REST Client - Postman
Access the REST endpoint at
/test/hello

The response
Testing with REST Client - WebBrowser
Testing with REST Client - WebBrowser
Testing with REST Client - WebBrowser

Access the REST endpoint at


/test/hello
Testing with REST Client - WebBrowser

Access the REST endpoint at


/test/hello

The response
Web Browser vs Postman
Web Browser vs Postman
• For simple REST testing for GET requests
Web Browser vs Postman
• For simple REST testing for GET requests

• Web Browser and Postman are similar


Web Browser vs Postman
• For simple REST testing for GET requests

• Web Browser and Postman are similar

• However, for advanced REST testing: POST, PUT etc …


Web Browser vs Postman
• For simple REST testing for GET requests

• Web Browser and Postman are similar

• However, for advanced REST testing: POST, PUT etc …

• Postman has much better support


Web Browser vs Postman
• For simple REST testing for GET requests

• Web Browser and Postman are similar

• However, for advanced REST testing: POST, PUT etc …

• Postman has much better support

• POSTing JSON data, setting content type


Web Browser vs Postman
• For simple REST testing for GET requests

• Web Browser and Postman are similar

• However, for advanced REST testing: POST, PUT etc …

• Postman has much better support

• POSTing JSON data, setting content type

• Passing HTTP request headers, authentication etc …


Spring REST Controller - Dev Process

m
Development Process
Development Process

1. Add Maven dependency for Spring MVC and Jackson project


Development Process

1. Add Maven dependency for Spring MVC and Jackson project

2. Add code for All Java Config: @Configuration


Development Process

1. Add Maven dependency for Spring MVC and Jackson project

2. Add code for All Java Config: @Configuration

3. Add code for All Java Config: Servlet Initializer


Development Process

1. Add Maven dependency for Spring MVC and Jackson project

2. Add code for All Java Config: @Configuration

3. Add code for All Java Config: Servlet Initializer

4. Create Spring REST Service using @RestController


Step 1: Add MavenDependencies
File: pom.xml

<!-- Add Spring MVC and REST support -->


<dependency>
<groupId>org.springframework</groupId
>
<artifactId>spring-
webmvc</artifactId>
<version>...</version>
</dependency>
<!-- Add Jackson for JSON converters -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId
>
<artifactId>jackson-databind</artifactId>
<version>...</version>
</dependency>
<!-- Add Servlet support for
Spring's AbstractAnnotationConfigDispatcherServletInitializer -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>...</version>
</dependency>
Step 1: Add MavenDependencies
File: pom.xml

Will load all supporting


<!-- Add Spring MVC and REST support --> dependencies:
<dependency>
<groupId>org.springframework</groupId spring-core, logging etc …
>
<artifactId>spring-
webmvc</artifactId>
<version>...</version>
</dependency>
<!-- Add Jackson for JSON converters -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId
>
<artifactId>jackson-databind</artifactId>
<version>...</version>
</dependency>
<!-- Add Servlet support for
Spring's AbstractAnnotationConfigDispatcherServletInitializer -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>...</version>
</dependency>
Step 1: Add MavenDependencies
File: pom.xml

<!-- Add Spring MVC and REST support -->


<dependency>
<groupId>org.springframework</groupId
>
<artifactId>spring-
webmvc</artifactId>
<version>...</version>
</dependency>
<!-- Add Jackson for JSON converters -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId
Add Jackson support
> we’ll need it later for converting
<artifactId>jackson-databind</artifactId>
<version>...</version> JSON <--> POJO
</dependency>
<!-- Add Servlet support for
Spring's AbstractAnnotationConfigDispatcherServletInitializer -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>...</version>
</dependency>
Step 1: Add MavenDependencies
File: pom.xml

<!-- Add Spring MVC and REST support -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>...</version>
</dependency>

<!-- Add Jackson for JSON converters -->


<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>...</version>
</dependency>

<!-- Add Servlet support for


Spring's AbstractAnnotationConfigDispatcherServletInitializer -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-
api</artifactId> Add Servlet support
<version>...</version>
</dependency>
Step 2:All Java Config: @Configuration
File: DemoAppConfig.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.luv2code.springdemo"
) public class DemoAppConfig {

}
Web App Initializer
Web App Initializer

• Spring MVC provides support for web app initialization


Web App Initializer

• Spring MVC provides support for web app initialization

• Makes sure your code is automatically detected


Web App Initializer

• Spring MVC provides support for web app initialization

• Makes sure your code is automatically detected

• Your code is used to initialize the servlet container


Web App Initializer

• Spring MVC provides support for web app initialization

• Makes sure your code is automatically detected

• Your code is used to initialize the servlet container

AbstractAnnotationConfigDispatcherServletInitializer
Web App Initializer (more info)

AbstractAnnotationConfigDispatcherServletInitializer
Web App Initializer (more info)

AbstractAnnotationConfigDispatcherServletInitializer

• Your TO DO list
Web App Initializer (more info)

AbstractAnnotationConfigDispatcherServletInitializer

• Your TO DO list

• Extend this abstract base class


Web App Initializer (more info)

AbstractAnnotationConfigDispatcherServletInitializer

• Your TO DO list

• Extend this abstract base class

• Override required methods


Web App Initializer (more info)

AbstractAnnotationConfigDispatcherServletInitializer

• Your TO DO list

• Extend this abstract base class

• Override required methods

• Specify servlet mapping and location of your app config


Step 3:All Java Config: Servlet Initializer
File:MySpringMvcDispatcherServletInitializer.java

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer


{
@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}

@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { DemoAppConfig.class };
}

@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}

}
Step 3:All Java Config: Servlet Initializer
File:MySpringMvcDispatcherServletInitializer.java

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer


{
@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}

@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { DemoAppConfig.class };
}

@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}

}
Step 3:All Java Config: Servlet Initializer
File:MySpringMvcDispatcherServletInitializer.java

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer


{
@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}

@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { DemoAppConfig.class };
}

@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}

}
Step 3:All Java Config: Servlet Initializer
File:MySpringMvcDispatcherServletInitializer.java

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer


{
@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}

@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { DemoAppConfig.class };
}

@Override
protected String[] getServletMappings() {
return new String[] { "/" };
Our config class
} from Step 2
}
Step 3:All Java Config: Servlet Initializer
File:MySpringMvcDispatcherServletInitializer.java

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer


{
@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}

@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { DemoAppConfig.class };
}

@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}

}
Step 3:All Java Config: Servlet Initializer
File:MySpringMvcDispatcherServletInitializer.java

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer


{
@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}

@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { DemoAppConfig.class };
}

@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}

}
Whew!!!!

Now for the easy stuff

Create Spring REST Controller

easy peazy …
Step 4: Create Spring REST Service
Step 4: Create Spring REST Service

@RestController
@RequestMapping("/test")
public class DemoRestController {

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

}
Spring REST Service - Students

m
Create a NewService
Create a NewService

• Return a list of students


Create a NewService

• Return a list of students

GET /api/students Returns a list of students


Spring REST Service
Spring REST Service

REST
Client
Spring REST Service

REST REST
Client Service
Spring REST Service

/api/students
REST REST
Client Service
Spring REST Service

/api/students
REST REST
Client Service
Spring REST Service We will write
this code

/api/students
REST REST
Client Service
Spring REST Service We will write
this code

/api/students
REST REST
Client Service

Web Browser
Or
Postman
Convert Java POJO to JSON
Convert Java POJO to JSON

• Our REST Service will return List<Student>


Convert Java POJO to JSON

• Our REST Service will return List<Student>

• Need to convert List<Student> to JSON


Convert Java POJO to JSON

• Our REST Service will return List<Student>

• Need to convert List<Student> to JSON

• Jackson can help us out with this …


Spring and Jackson Support
Spring and Jackson Support

• Spring will automatically handle Jackson integration


Spring and Jackson Support

• Spring will automatically handle Jackson integration

• As long as the Jackson project is on the classpath or pom.xml


Spring and Jackson Support

• Spring will automatically handle Jackson integration

• As long as the Jackson project is on the classpath or pom.xml

• JSON data being passed to REST controller is converted to Java POJO


Spring and Jackson Support

• Spring will automatically handle Jackson integration

• As long as the Jackson project is on the classpath or pom.xml

• JSON data being passed to REST controller is converted to Java POJO

• Java POJO being returned from REST controller is converted to JSON


Spring and Jackson Support Happens
automatically
behind the scenes
• Spring will automatically handle Jackson integration

• As long as the Jackson project is on the classpath or pom.xml

• JSON data being passed to REST controller is converted to Java POJO

• Java POJO being returned from REST controller is converted to JSON


Student POJO (class)
Student POJO (class)
Student POJO (class)

Java
POJO

Student
Jackson Data Binding
Jackson Data Binding

• Jackson will call appropriate getter/setter method


Jackson Data Binding

• Jackson will call appropriate getter/setter method

{
"id": 14,

"firstName": "Mario",

"lastName": "Rossi",

"active": true
}
Jackson Data Binding

• Jackson will call appropriate getter/setter method

{
"id": 14,
Java
"firstName": "Mario", POJO
"lastName": "Rossi",

"active": true
}
Student
Jackson Data Binding

• Jackson will call appropriate getter/setter method

{
"id": 14,
Java
"firstName": "Mario", POJO
"lastName": "Rossi",

"active": true
}
Student
Jackson Data Binding

• Jackson will call appropriate getter/setter method

{
"id": 14,
Java
"firstName": "Mario", POJO
"lastName": "Rossi",

"active": true
}
Student
Jackson Data Binding

• Jackson will call appropriate getter/setter method

{
"id": 14,
Java
"firstName": "Mario", POJO
"lastName": "Rossi",

"active": true
}
Student
Jackson will do
this work
Spring REST Service
Spring REST Service

REST
Client
Spring REST Service

REST REST
Client Service
Spring REST Service

/api/students
REST REST
Client Service
Spring REST Service We will write
this code

/api/students
REST REST
Client Service
Spring REST Service We will write
this code

/api/students
REST REST
Client Service

List<Student>
Spring REST Service We will write
this code

/api/students
REST REST
Client Service

List<Student>
Spring REST Service We will write
this code

/api/students
REST REST
Client Service

List<Student>

Jackson will
convert to
JSON array
Behind the scenes We will write
this code

REST REST
Client Service
Behind the scenes We will write
this code

REST /api/students
REST
Client Service
Behind the scenes We will write
this code

Spring
REST
REST /api/students
REST
Client Jackson
Service
Behind the scenes We will write
this code

Spring
REST
REST /api/students
REST
Client Jackson
Service
Behind the scenes We will write
this code

Spring
REST
REST /api/students
REST
Client Jackson
Service

We will return
List<Student>
Behind the scenes We will write
this code

Spring
REST
REST /api/students
REST
Client Jackson
Service

We will return
List<Student>
Behind the scenes We will write
this code

Spring
REST
REST /api/students
REST
Client Jackson
Service

We will return
Jackson will convert
List<Student>
List<Student> to
JSON array
Behind the scenes We will write
this code

Spring
REST
REST /api/students
REST
Client Jackson
Service

We will return
Jackson will convert
List<Student>
List<Student> to
JSON array
Development Process
Development Process

1. Create Java POJO class for Student


Development Process

1. Create Java POJO class for Student

2. Create Spring REST Service using @RestController


Step 1: Create Java POJO class forStudent
Step 1: Create Java POJO class forStudent
Step 1: Create Java POJO class forStudent
File: Student.java

public class Student {

private String firstName;


private String lastName;

public Student() {

public Student(String firstName, String lastName) {


this.firstName = firstName;
this.lastName = lastName;
}

public String getFirstName() {


return firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

}
Step 1: Create Java POJO class forStudent
File: Student.java

public class Student {


Fields
private String firstName;
private String lastName;
Constructors
public Student() { Getter/Setters
}

public Student(String firstName, String lastName) {


this.firstName = firstName;
this.lastName = lastName;
}

public String getFirstName() {


return firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

}
Step 2: Create @RestController
Step 2: Create @RestController
Step 2: Create @RestController
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class StudentRestController {
Step 2: Create @RestController
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class StudentRestController {

// define endpoint for "/students" - return list of students


Step 2: Create @RestController
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class StudentRestController {

// define endpoint for "/students" - return list of students

@GetMapping("/students")
public List<Student> getStudents() {
Step 2: Create @RestController
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class StudentRestController {

// define endpoint for "/students" - return list of students

@GetMapping("/students")
public List<Student> getStudents() {

List<Student> theStudents = new ArrayList<>();


Step 2: Create @RestController
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class StudentRestController {

// define endpoint for "/students" - return list of students

@GetMapping("/students") We'll hard code


public List<Student> getStudents() {
for now …
List<Student> theStudents = new ArrayList<>();
can add DB later …
theStudents.add(new Student("Poornima", "Patel"));
theStudents.add(new Student("Mario", "Rossi"));
theStudents.add(new Student("Mary", "Smith"));
Step 2: Create @RestController
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class StudentRestController {

// define endpoint for "/students" - return list of students

@GetMapping("/students")
public List<Student> getStudents() {

List<Student> theStudents = new ArrayList<>();

theStudents.add(new Student("Poornima", "Patel"));


theStudents.add(new Student("Mario", "Rossi"));
theStudents.add(new Student("Mary", "Smith")); Jackson will convert
return theStudents; List<Student> to
}
JSON array
}
Spring REST - Path Variables

m
Path Variables
Path Variables

• Retrieve a single student by id


Path Variables

• Retrieve a single student by id

GET /api/students/{studentId} Retrieve a single student


Path Variables

• Retrieve a single student by id

GET /api/students/{studentId} Retrieve a single student

Known as a
"path variable"
Path Variables

• Retrieve a single student by id

GET /api/students/{studentId} Retrieve a single student

/api/students/0 Known as a
/api/students/1 "path variable"

/api/students/2
Spring REST Service
Spring REST Service

REST
Client
Spring REST Service

REST REST
Client Service
Spring REST Service

/api/students/{studentId}
REST REST
Client Service
Spring REST Service

/api/students/{studentId}
REST REST
Client Service
{
"firstName": "Mario",
"lastName": "Rossi"
}
Spring REST Service We will write
this code

/api/students/{studentId}
REST REST
Client Service
{
"firstName": "Mario",
"lastName": "Rossi"
}
Spring REST Service We will write
this code

/api/students/{studentId}
REST REST
Client Service
{
"firstName": "Mario",
"lastName": "Rossi"
} Student
Spring REST Service We will write
this code

/api/students/{studentId}
REST REST
Client Service
{
"firstName": "Mario",
"lastName": "Rossi"
} Student

Jackson will
convert to
JSON
Behind the scenes We will write
this code

REST REST
Client Service
Behind the scenes We will write
this code

REST /api/students/{studentId}
REST
Client Service
Behind the scenes We will write
this code

Spring
REST
REST /api/students/{studentId}
REST
Client Jackson
Service
Behind the scenes We will write
this code

Spring
REST
REST /api/students/{studentId}
REST
Client Jackson
Service
Behind the scenes We will write
this code

Spring
REST
REST /api/students/{studentId}
REST
Client Jackson
Service

We will return
Student
Behind the scenes We will write
this code

Spring
REST
REST /api/students/{studentId}
REST
Client Jackson
Service

We will return
Student
Behind the scenes We will write
this code

Spring
REST
REST /api/students/{studentId}
REST
Client Jackson
Service

We will return
Jackson will convert Student
Student to
JSON
Behind the scenes We will write
this code

Spring
REST
REST /api/students/{studentId}
REST
Client Jackson
Service
{
"firstName": "Mario",
"lastName": "Rossi"
}

We will return
Jackson will convert Student
Student to
JSON
Development Process
Development Process

1. Add equest ppi g to Sp i g REST Se ice


Development Process

1. Add request mapping to Spring REST Service

๏ Bind path variable to method parameter using @PathVariable


Step 1: Add Request Mapping
Step 1: Add Request Mapping
File: StudentRestController.java

@RestController
@RequestMapping( /api )
public class StudentRestController {
Step 1: Add Request Mapping
File: StudentRestController.java

@RestController
@RequestMapping( /api )
public class StudentRestController {

// define endpoint for /students/{studentId} return student at index


Step 1: Add Request Mapping
File: StudentRestController.java

@RestController
@RequestMapping( /api )
public class StudentRestController {

// define endpoint for /students/{studentId} return student at index

@GetMapping( /students/{studentId} )
public Student getStudent(@PathVariable int studentId) {
Step 1: Add Request Mapping
File: StudentRestController.java

@RestController
@RequestMapping( /api )
public class StudentRestController {

// define endpoint for /students/{studentId} return student at index

@GetMapping( /students/{studentId} )
public Student getStudent(@PathVariable int studentId) {

Bind the path variable


(by default, must match)
Step 1: Add Request Mapping
File: StudentRestController.java

@RestController
@RequestMapping( /api )
public class StudentRestController {

// define endpoint for /students/{studentId} return student at index

@GetMapping( /students/{studentId} )
public Student getStudent(@PathVariable int studentId) {

List<Student> theStudents new ArrayList<>()


Step 1: Add Request Mapping
File: StudentRestController.java

@RestController
@RequestMapping( /api )
public class StudentRestController {

// define endpoint for /students/{studentId} return student at index

@GetMapping( /students/{studentId} )
public Student getStudent(@PathVariable int studentId) {

List<Student> theStudents new ArrayList<>()

// populate theStudents
Step 1: Add Request Mapping
File: StudentRestController.java

@RestController
@RequestMapping( /api )
public class StudentRestController {

// define endpoint for /students/{studentId} return student at index

@GetMapping( /students/{studentId} ) Keep it simple,


public Student getStudent(@PathVariable int s tu den t Id ) {
j u s t i n d e x intothelist
List<Student> theStudents new ArrayList<>()

// populate theStudents We’ll do fancy DB stuff later

return theStudents get(studentId)


}
Step 1: Add Request Mapping
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class StudentRestController {

// define endpoint for "/students/{studentId}" - return student at index

@GetMapping("/students/{studentId}")
public Student getStudent(@PathVariable int studentId) {

List<Student> theStudents = new ArrayList<>();

// populate theStudents

return theStudents.get(studentId);
Jackson will convert
} Student to JSON
}
"At the conclusion of this chapter, ensure
completion of all exercises related to REST API
Interview Questions and practice to all Lab
sessions ."

Reading assignment: REST error handling

You might also like