Spring SpringBoot Web MVC Module
Spring SpringBoot Web MVC Module
Web/MVC
Modules
A Spring MVC provides an elegant solution to use MVC in spring framework by the
help of DispatcherServlet. Here, DispatcherServlet is a class that receives the incoming
request and maps it to the right resource such as controllers, models, and views.
Spring Boot is well suited for web application development. You can create a self-contained
HTTP server by using embedded Tomcat, Jetty, Undertow, or Netty. Most web applications
use the SpringBoot-starter-web module to get up and running quickly.
What is MVC?
MVC stands for Model-View-Controller, and it is a widely used architectural pattern in
software development, particularly for building user interfaces and web applications. MVC is
designed to separate an application into three interconnected components, each with a
specific responsibility:
MVC Architecture becomes so popular that now most of the popular frameworks
follow the MVC design pattern to develop the applications. Some of the popular Frameworks
that follow the MVC Design pattern are:
Model:
The Model component corresponds to all the data-related logic that the user works
with. This can represent either the data that is being transferred between the View and
Controller components or any other business logic-related data. For example, a Customer
object will retrieve the customer information from the database, manipulate it and update it
data back to the database or use it to render data.
View:
The View component is used for all the UI logic of the application. For example, the
Customer view will include all the UI components such as text boxes, dropdowns, etc. that
the final user interacts with.
Controller:
Controllers act as an interface between Model and View components to process all
the business logic and incoming requests, manipulate data using the Model component and
interact with the Views to render the final output. For example, the Customer controller will
handle all the interactions and inputs from the Customer View and update the database using
the Customer Model. The same controller will be used to view the Customer data.
1. A user interacts with the View (e.g., clicks a button or submits a form).
2. The View forwards the user input to the Controller.
3. The Controller processes the input, potentially querying or updating the Model.
4. The Model is updated if necessary, and the Controller retrieves data from the Model.
5. The Controller sends the updated data to the View.
6. The View renders the data and presents it to the user.
• Separate roles - The Spring MVC separates each role, where the model object, controller,
view resolver, DispatcherServlet, validator, etc. can be fulfilled by a specialized object.
• Light-weight - It uses light-weight servlet container to develop and deploy your
application.
• Powerful Configuration - It provides a robust configuration for both framework and
application classes that includes easy referencing across contexts, such as from web
controllers to business objects and validators.
• Rapid development - The Spring MVC facilitates fast and parallel development.
• Reusable business code - Instead of creating new objects, it allows us to use the existing
business objects.
• Easy to test - In Spring, generally we create JavaBeans classes that enable you to inject
test data using the setter methods.
• Flexible Mapping - It provides the specific annotations that easily redirect the page.
In Next Page, Add Spring Boot Modules/Starters as shown below and click on finish.
Now Run your Application as Spring Boot App / java application from Main Method
Class.
Controller Class:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloWorldController {
@GetMapping("/world")
@ResponseBody
public String printHelloWrold() {
return "Hello world! Welcome to Spring Boot MVC";
}
}
Execute/Call above Endpoint: We will access Endpoints/URLs from Http Clients like Browsers.
Now open application. Properties file and add below predefined properties and provide
required values.
server.port=8899
server.servlet.context-path= /hello
➢ Restart our application again, application started on port(s): 8899 (http) with context
path '/hello'
Internal Workflow of Spring MVC Application i.e., Request & Response Handling:
Front Controller:
A front controller is defined as a controller that handles all requests for a Web
Application. DispatcherServlet servlet is the front controller in Spring MVC that intercepts
every request and then dispatches requests to an appropriate controller. The
DispatcherServlet is a Front Controller and one of the most significant components of the
Spring MVC web framework. A Front Controller is a typical structure in web applications that
receives requests and delegates their processing to other components in the application. The
DispatcherServlet acts as a single entry point for client requests to the Spring MVC web
application, forwarding them to the appropriate Spring MVC controllers for processing.
Request: The first step in the MVC flow is when a request is received by the Dispatcher Servlet.
The aim of the request is to access a resource on the server.
Response: Response is made by a server to a client. The aim of the response is to provide the
client with the resource it requested, or inform the client that the action it requested has been
carried out; or else to inform the client that an error occurred in processing its request.
Dispatcher Servlet: Now, the DispatcherServlet with the help of Handler Mappings
understands the Controller class name associated with the received request. Once the
DispatcherServlet knows which Controller will be able to handle the request, it will transfer
the request to it. DispatcherServlet expects a WebApplicationContext (an extension of a
plain ApplicationContext) for its own configuration. WebApplicationContext has a link to the
ServletContext and the Servlet with which it is associated.
The DispatcherServlet delegates to special beans to process requests and render the
appropriate responses.
HandlerMapping:
In Spring MVC, the DispatcherServlet acts as front controller – receiving all incoming HTTP
requests and processing them. Simply put, the processing occurs by passing the requests to
the relevant component with the help of handler mappings.
Now Define Controller classes inside our Spring Boot MVC application:
package com.apple.iphone.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class IphoneCotroller {
@GetMapping("/message")
@ResponseBody
public String printIphoneMessage() {
//Logic of Method
return " Welcome to Iphone World.";
}
@GetMapping("/cost")
@ResponseBody
public String printIphone14Cost() {
return " Price is INR : 150000";
}
}
package com.apple.iphone.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class IpadControlller {
@GetMapping("/ipad/cost")
@ResponseBody
Now when we start our project as Spring Boot Application, Internally Project deployed to
tomcat server and below steps will be executed.
• When we are started/deployed out application, Spring MVC internally creates
WebApplcationContext i.e. Spring Container to instantiate and manage all Spring Beans
associated to our project.
• Spring instantiates Pre-Defined Front Controller class called as DispatcherServlet as well
as WebApplicationContext scans all our packages for @Component, @Controller etc..
and other Bean Configurations.
• Spring MVC WebApplicationContext will scan all our Controller classes which are marked
with @Controller and starts creating Handler Mappings of all URL patterns defined in side
controller classes with Controller and endpoint method names mappings.
Controller Class:
In Spring Boot, the controller class is responsible for processing incoming HTTP web
requests, preparing a model, and returning the view to be rendered as a response on client.
The controller classes in Spring are annotated either by the @Controller or the
@RestController annotation.
@Controller: org.springframework.stereotype.Controller
@ResponseBody:
Package: org.springframework.web.bind.annotation.ResponseBody:
@RequestMapping:
Package: org.springframework.web.bind.annotation.RequestMapping
This Annotation for mapping web requests onto methods in request-handling classes i.e.
controller classes with flexible method signatures. @RequestMapping is Spring MVC's most
common and widely used annotation.
consumes = "text/plain"
consumes = {"text/plain", "application/*"}
consumes = MediaType.TEXT_PLAIN_VALUE
produces String[] mapping by media types that can be produced by the mapped
handler. Consists of one or more media types one of which
must be chosen via content negotiation against the
"acceptable" media types of the request.
produces = "text/plain"
produces = {"text/plain", "application/*"}
produces = MediaType.TEXT_PLAIN_VALUE
produces = "text/plain;charset=UTF-8"
Note: This annotation can be used both at the class and at the method level. In most cases, at
the method level, applications will prefer to use one of the HTTP method specific variants
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping.
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class IphoneCotroller {
@RequestMapping("/message")
@ResponseBody
public String printIphoneMessage() {
return " Welcome to Ihpne World.";
}
}
@RequestMapping("/message"):
1. If we are not defined in method type attribute and value, then same handler method will
be executed for all HTTP methods along with endpoint.
2. @RequestMapping("/message") is equivalent to @RequestMapping(value="/message")
or @RequestMapping(path="/message")
i.e. value and path are same type attributes to configure URI path of handler method. We
can use either of them i.e. value is an alias for path.
Now above handler method will work only for HTTP GET request call. If we try to request with
any HTTP methods other than GET, we will get error response as
"status": 405,
"error": "Method Not Allowed",
@RequestMapping(value="/message",
method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public String printIphoneMessage() {
return " Welcome to Iphone World.";
}
Now above handler method will work only for HTTP GET and POST requests calls. If we try to
request with any HTTP methods other than GET, POST we will get error response as:
"status": 405,
"error": "Method Not Allowed",
i.e. we can configure one URL handler method with multiple HTTP
methods request.
Above handler method will support both GET and POST requests of URI’s mappings
"/message", "/msg/iphone".
RequestMethod:
RequestMethod is Enumeration(Enum) of HTTP request methods. Intended for use
with the RequestMapping.method() attribute of the RequestMapping annotation.
ENUM Constant Values : GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, TRACE
We can Define Same URI with multiple different handler/controller methods for different
HTTP methods. Depends on incoming HTTP method request type specific handler method will
be executed.
We can use @RequestMapping with class definition level to create the base URI of
that specific controller i.e. All URI mappings of that controller will be preceded with class level
URI value always.
For example:
package com.apple.iphone.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/ipad")
public class IpadControlller {
@GetMapping("/cost")
@ResponseBody
public String printIPadCost() {
return " Ipad Price is INR : 200000";
}
@GetMapping("/model")
From above example, class level Request mapping value ("/ipad") will be base URI for all
handler method URI values. Means All URIs starts with /ipad of the controller URI’s as shown
below.
http://localhost:6655/apple/ipad/model
http://localhost:6655/apple/ipad/cost
@GetMapping:
Package: org.springframework.web.bind.annotation.GetMapping
This Annotation used for mapping HTTP GET requests onto specific handler methods.
The @GetMapping annotation is a composed version of @RequestMapping annotation that
acts as a shortcut for @RequestMapping(method = RequestMethod.GET).
The @GetMapping annotated methods handle the HTTP GET requests matched with the
given URI value.
Similar to this annotation, we have other Composed Annotations to handle different HTTP
methods.
@PostMapping:
This Annotation used for mapping HTTP POST requests onto specific handler methods.
@PostMapping is a composed annotation that acts as a shortcut for
@RequestMapping(method = RequestMethod.POST).
@PutMapping:
This Annotation used for mapping HTTP PUT requests onto specific handler methods.
@PutMapping is a composed annotation that acts as a shortcut for
@RequestMapping(method = RequestMethod.PUT).
@DeleteMapping:
This Annotation used for mapping HTTP DELETE requests onto specific handler
methods. @DeleteMapping is a composed annotation that acts as a shortcut for
@RequestMapping(method = RequestMethod.DELETE).
➢ By default embedded tomcat server will not support JSP functionalities inside a Spring
Boot MVC application. So, In order to work with JSP, we need to add below dependency in
Spring boot MVC.
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
What is ViewResolver?
In Spring MVC, a ViewResolver is an essential component responsible for resolving
logical view names returned by controller methods into actual view implementations that can
be rendered and returned to the client. It plays a crucial role in the web application's flow by
mapping logical view names to views, which can be JSP pages, HTML templates, or any other
type of view technology supported by Spring.
InternalResourceViewResolver:
1. Controller Returns a Logical View Name: In a Spring web application, when a controller
method processes an HTTP request and returns a logical view name (e.g., "home" or
"dashboard"), this logical view name is returned to the Spring MVC framework.
➢ Add below View resolver properties in application.properties file to configure view names
i.e. JSP files.
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
➢ Based on above configuration of property prefix value, we have to create folders inside
our Spring Boot MVC application.
➢ Create a folder webapp inside src -> main
➢ Inside webapp, create another folder WEB-INF
➢ Inside WEB-INF, create another folder view
➢ Inside view Folder, We will create our JSP files.
➢ Now create a JSP file inside view folder and invoke it from Controller Method.
<html>
<head>
<title>Spring Boot MVC</title>
</head>
<body>
<h1>Welcome to Spring Boot MVC with JSP</h1>
</body>
package com.facebook.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class UserController {
@GetMapping("/welcome")
public String sayHello() {
return "hello";
}
}
Internally, DispatcherServlet will forwards the request to jsp file as per our Internal
Resource View Resolver configuration data, i.e. inside folder /WEB-INF/view/ with suffix
.jsp by including jsp file name “hello”.
We are going annotate with @Service is annotated on class to say spring, this is my Service
Layer.
Create An Example with Service Layer:
Controller Class:
@Controller
@RequestMapping("/admission")
public class UniversityAdmissionsController {
//Logic
Service Class:
@Service
public class UniversityAdmissionsService {
//Logic
Now integrate Service Layer class with Controller Layer i.e. injecting Service class Object into
Controller class Object. So we will use @Autowired annotation to inject service in side
controller.
@Controller
public class UniversityAdmissionsController {
//Logic
}
From above, We are integrated controller with service layer. Now inside Service class, we will
write Business Logic and then data should be passed to persistence layer.
Now return values of service class methods are passed to Controller class level. This is how
we are using service layer with controller layer. Now we should integrate Service layer with
DAO Layer to Perform DB operations. We will have multiple examples together of all three
layer.
Repository Layer:
Repository Layer is mainly used for managing the data with database in a Spring
Application. A huge amount of code is required for working with the databases, which can be
easily reduced by Spring Data modules. It consists of JPA and JDBC modules. There are many
Spring applications that use JPA technology, so these development procedures can be easily
simplified by Spring Data JPA. As we discussed earlier in JPA functionalities, Now we have to
integrate JPA Module to our existing application.
Repository Interface:
@Respository
public interface AdmissionsRepository extends JpaRepository {
//JPA Methods
}
@Service
public class UniversityAdmissionsService {
//Logic
Requirement: Create a Project and implement User Registration and Login Flows.
server.port=9999
server.servlet.context-path=/tekteacher
#DB Properties.
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=c##dilip
spring.datasource.password=dilip
spring.jpa.show-sql=true
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
server.port=9999
server.servlet.context-path=/tekteacher
#DB Properties.
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=c##dilip
spring.datasource.password=dilip
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
#JSP
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
<html>
<head>
<title> User Register</title>
</head>
<body>
<form action="user/register" method="POST">
Name : <input type="text" name="name" /> <br />
Email Id : <input type="text" name="email" /> <br />
Contact Number : <input type="text" name="contact" /> <br />
Password : <input type="password" name="pwd" /> <br />
<input type="submit" value="Register" /> <br />
</form>
</body>
</html>
Create another JSP file for User Registration Result Message, whether User Account
Created or Not : result.jsp
Create a DTO class for retrieving details from HttpServeletRequest Object in side
Controller method.
package com.tek.teacher.dto;
Create Controller class and Methods for loading User Registration Page and reading data
from Registration page. Once Receiving Data at controller we should store it inside
database.
package com.tek.teacher.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import com.tek.teacher.dto.UserReigtserDto;
import com.tek.teacher.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
@Controller
public class UserController {
@Autowired
UserService userService;
return modelAndView;
}
}
Now Create Service Layer class and respective method for storing User Information inside
database.
package com.tek.teacher.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tek.teacher.dto.UserReigtserDto;
import com.tek.teacher.entity.UsersInfo;
import com.tek.teacher.repository.UserRepository;
@Service
public class UserService {
@Autowired
UserRepository repository;
Now create JPA Entity class for Database Operations, with columns related to User Details.
package com.tek.teacher.entity;
@Entity
@Table
public class UsersInfo{
@Id
@Column
private String emailId;
@Column
private String name;
@Column
private String contact;
@Column
private String password;
package com.tek.teacher.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.tek.teacher.entity.UsersInfo;
@Repository
public interface UserRepository extends JpaRepository<UsersInfo, String>{
Now Enter User Information and then click on Register button. Internally it will trigger
another endpoint “user/register”
<html>
<head>
<title>Login User</title>
</head>
<body>
<form action="loginCheck" method="POST">
Email : <input type="text" name="email" /> <br />
Password : <input type="password" name="pwd" /> <br />
<input type="submit" value="Login" /> <br />
</form>
</body>
</html>
Now Create Controller Method For Receiving Login Form Data and validation of User
Details.
@PostMapping("/loginCheck")
public ModelAndView validateUser(HttpServletRequest request) {
package com.facebook.repository;
@Repository
public interface UserRepository extends JpaRepository<FacebookUsers, String>{
Response :
Response :
Generally we will choose HTTP method depends on Data Base Operations of the
requirement i.e. When we are implementing Handler methods finally as part of implantation
which database query is executed as explained as follows.
Create, Read, Update, and Delete — or CRUD — are the four major functions used to
interact with database applications. The acronym is popular among programmers, as it
provides a quick reminder of what data manipulation functions are needed for an application
Although there are numerous definitions for each of the CRUD functions, the basic idea is that
they accomplish the following in a collection of data:
Read Retrieves entries that match certain criteria (if there are any) Select
Generally most of the time we will choose HTTP methods of an endpoint based on
Requirement Functionality performing which operation out of CRUD operations. This is a best
practice of creating REST API’s.
CRUD HTTP
CREATE POST
READ GET
UPDATE PUT
DELETE DELETE
Webservices:
Web services are a standardized way for different software applications to
communicate and exchange data. They enable interoperability between various systems,
regardless of the programming languages or platforms they are built on. Web services use a
set of protocols and technologies to enable communication and data exchange between
different applications, making it possible for them to work together without any issues.
SOAP is a protocol for exchanging structured information using XML. It provides a way
for applications to communicate by sending messages in a predefined format. SOAP web
services offer a well-defined contract for communication and are often used in enterprise-
level applications due to their security features and support for more complex scenarios.
REST is an architectural style that uses HTTP methods (GET, POST, PUT, DELETE) to
interact with resources in a stateless manner. RESTful services are simple, lightweight, and
widely used due to their compatibility with the HTTP protocol. They are commonly used for
building APIs that can be consumed by various clients, such as web and mobile applications.
The choice of web service type depends on factors such as the nature of the application, the
level of security required, the complexity of communication, and the preferred data format.
REST API:
RESTful API is an interface that two computer systems use to exchange information
securely over the internet. Most business applications have to communicate with other
internal and third-party applications to perform various tasks.
API: An API is a set of definitions and protocols for building and integrating application
software. It’s sometimes referred to as a contract between an information provider and an
information consumer. An application programming interface (API) defines the rules that you
must follow to communicate with other software systems. Developers expose or create APIs
so that other applications can communicate with their applications programmatically. For
example, the ICICI application exposes an API that asks for banking users, Card Details , Name,
CVV etc.. When it receives this information, it internally processes the users data and returns
the payment status.
REST is a set of architectural style but not a protocol or a standard. API developers
can implement REST in a variety of ways. When a client request is made via a RESTful API, it
transfers a representation of the state of the resource to the requester or endpoint. This
information or representation is delivered in one of several formats like JSON or XML via HTTP
Protocol.
REST API architecture that imposes conditions on how an API should work. REST was
initially created as a guideline to manage communication on a complex network like the
internet. You can use REST-based architecture to support high-performing and reliable
communication at scale. You can easily implement and modify it, bringing visibility and cross-
platform portability to any API system.
Clients: Clients are users who want to access information from the web. The client can
be a person or a software system that uses the API. For example, developers can write
programs that access weather data from a weather system. Or you can access the same data
from your browser when you visit the weather website directly.
Resources: Resources are the information that different applications provide to their
clients/users. Resources can be images, videos, text, numbers, or any type of data. The
machine that gives the resource to the client is also called the server. Organizations use APIs
to share resources and provide web services while maintaining security, control, and
authentication. In addition, APIs help them to determine which clients get access to specific
internal resources.
API developers can design APIs using several different architectures. APIs that follow the REST
architectural style are called REST APIs. Web services that implement REST architecture are
called RESTful web services. The term RESTful API generally refers to RESTful web APIs.
However, you can use the terms REST API and RESTful API interchangeably.
The following are some of the principles of the REST architectural style:
Uniform Interface: The uniform interface is fundamental to the design of any RESTful
webservice. It indicates that the server transfers information in a standard format. The
formatted resource is called a representation in REST. This format can be different from the
internal representation of the resource on the server application. For example, the server can
store data as text but send it in an HTML representation format.
Layered system: In a layered system architecture, the client can connect to other authorized
intermediate services between the client and server, and it will still receive responses from
the server. Sometimes servers can also pass on requests to other servers. You can design your
RESTful web service to run on several servers with multiple layers such as security,
application, and business logic, working together to fulfil client requests. These layers remain
invisible to the client. We can achieve this as part of Micro Services Design.
Scalability: Systems that implement REST APIs can scale efficiently because REST optimizes
client-server interactions. Statelessness removes server load because the server does not
have to store past client request information.
Platform and Language Independence: REST APIs are platform and language independent,
meaning they can be consumed by a wide range of clients, including web browsers, mobile
devices, and other applications. As long as the client can send HTTP requests and understand
the response, it can interact with a REST API regardless of the technology stack used on the
server side. You can write both client and server applications in various programming
languages without affecting the API design. We can also change the technology on both sides
without affecting the communication.
Overall, REST APIs provide a simple, scalable, and widely supported approach to building web
services. These advantages in terms of simplicity, platform independence, scalability,
flexibility, and compatibility make REST as a popular choice for developing APIs in various
domains, from web applications to mobile apps and beyond.
The basic function of a RESTful API is the same as browsing the internet. The client contacts
the server by using the API when it requires a resource. API developers explain how the client
should use the REST API in the server application with API documentation. These are the
general steps for any REST API call integration:
1. The client sends a request to the server. The client follows the API documentation to
format the request in a way that the server understands.
2. The server authenticates the client and Request and confirms that the client has the right
to make that request.
3. The server receives the request and processes it internally.
4. The server returns a response to the client. The response contains information that tells
the client whether the request was successful. The response also includes any information
that the client requested.
URI (Unique Resource Identifier) : The server identifies each resource with unique
resource identifiers. For REST services, the server typically performs resource identification
by using a Uniform Resource Locator (URL). The URL specifies the path to the resource. A URL
is similar to the website address that you enter into your browser to visit any webpage. The
URL is also called the request endpoint and clearly specifies to the server what the client
requires.
HTTP Method: Developers often implements RESTful APIs by using the Hypertext Transfer
Protocol (HTTP). An HTTP method tells the server what it needs to do with the resource. The
following are four common HTTP methods:
• GET: Clients use GET to access resources that are located at the specified URL on
the server.
• POST: Clients use POST to send data to the server. They include the data
representation with the request body. Sending the same POST request multiple times
has the side effect of creating the same resource multiple times.
• PUT: Clients use PUT to update existing resources on the server. Unlike POST,
sending the same PUT request multiple times in a RESTful web service gives the same
result.
• DELETE: Clients use DELETE request to remove the resource.
Data: REST API requests might include data for the POST, PUT, and other HTTP methods to
work successfully.
Parameters: RESTful API requests can include parameters that give the server more details
about what needs to be done. The following are some different types of parameters:
• Path parameters that specify URL details.
• Query/Request parameters that request more information about the resource.
• Cookie parameters that authenticate clients quickly.
REST principles require the server response to contain the following main components:
Status line: The status line contains a three-digit status code that communicates request
success or failure.
2XX codes indicate success
4XX and 5XX codes indicate errors
3XX codes indicate URL redirection.
Message body: The response body contains the resource representation. The server selects
an appropriate representation format based on what the request headers contain i.e. like
JSON/XML formats. Clients can request information in XML or JSON formats, which define
how the data is written in plain text. For example, if the client requests the name and age of
a person named John, the server returns a JSON representation as follows:
{
"name":"John",
"age":30
}
Headers: The response also contains headers or metadata about the response. They
give more context about the response and include information such as the server, encoding,
date, and content type.
As per REST API creation Guidelines, we should choose HTTP methods depends on the
Database Operation performed by our functionality, as We discussed previously.
Spring MVC is a popular framework for creating web applications in Java. Implementing
RESTful web services in Spring MVC involves using the Spring framework to create endpoints
that follow the principles of the REST architectural style. It can be used to create RESTful web
services, which are web services that use the REST architectural style.
RESTful services allow different software systems to communicate over the internet using
standard HTTP methods, like GET, POST, PUT, and DELETE. These services are based on a set
of principles that emphasize simplicity, scalability, and statelessness.
In REST Services implementation, Data will be represented as JOSN/XML type most of the
times. Now a days JSON is most popular data representational format to create and produce
REST Services.
JSON:
JSON stands for JavaScript Object Notation. JSON is a text format for storing and
transporting data. JSON is "self-describing" and easy to understand.
JSON is a lightweight data-interchange format. JSON is plain text written in JavaScript object
notation. JSON is used to exchange data between multiple applications/services. JSON is
language independent.
A name/value pair consists of a field name (in double quotes), followed by a colon, followed
by a value:
Example: "name" : "John"
o a string
o a number
o an object
o an array
o a Boolean
o null
JSON vs XML:
Both JSON and XML can be used to receive data from a web server. The following JSON and
XML examples both define an employee’s object, with an array of 3 employees:
JSON Example
{
"employees": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
]
}
XML Example:
<employees>
<employee>
<firstName>John</firstName>
<lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName>
<lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName>
When A Request Body Contains JSON/XML data Format, then how Spring MVC/JAVA
language handling Request data?
Here, We should Convert JSON/XML data to JAVA Object while Request landing on Controller
method, after that we are using JAVA Objects in further process. Similarly, Sometimes we have
to send Response back as either JSON or XML format i.e. JAVA Objects to JSON/XML Format.
For these conversions, we have few pre-defined solutions in Market like Jackson API, GSON
API, JAXB etc..
Note: we should carte Java POJO classes specific to JSON payload structure, to enable auto
conversion between JAVA and JSON.
JSON Payload: Below Json contains ARRY of String Data Type values
{
"student":[
"Dilip",
"Naresh",
"Mohan",
"Laxmi"
]
}
Java Class: JSON Array of String will be takes as List<String> with JSON key name.
import java.util.List;
{
"nareshIt": {
"students": [
{
"no": "1",
"name": "Dilip",
"mobile": 8826111377
},
{
"no": "2",
"name": "Naresh",
"mobile": 8125262702
}
]
}
}
Below picture showing how are creating JAVA classes from above payload.
Student.java
import java.util.ArrayList;
public class NareshIt {
private ArrayList<Student> students;
StudentsData.java
{
"student": [
{
"firstName": "Dilip",
"lastName": "Singh",
"mobile": 88888,
"pwd": "Dilip",
"emailID": "Dilip@Gmail.com"
},
{
"firstName": "Naresh",
"lastName": "It",
"mobile": 232323,
"pwd": "Naresh",
import com.fasterxml.jackson.annotation.JsonProperty;
Another class To Wrap above class Object as List with property name student as per JSON.
import java.util.List;
List<StudentInfo> student;
From the above JSON payload and JAVA POJO class, we can see a difference for one JSON
property called as emailID i.e. in JAVA POJO class property name we taken as email instead
of emailID. In Such case to map JSON to JAVA properties with different names, we use an
annotation called as @JsonProperty("jsonPropertyName").
@JsonProperty:
If you want to serialize this object to JSON and specify that the JSON property names should
be "first_name", "last_name", and "age", you can use the @JsonProperty annotation like this:
As a developer, we should always create POJO classes aligned to JSON payload to bind JOSN
data to Java Object with @RequestBody annotation.
To implement REST services in Spring MVC, you can use the @RestController annotation. This
annotation marks a class as a controller that returns data to the client in a RESTful way.
@RestController:
@GetMapping(path = "/mac/details")
@ResponseBody
public String getMacBookDetail() {
return "MAC Book Details : Price 200000. Model 2022";
}
@GetMapping(path = "/iphone/details")
@ResponseBody
public String getIphoneDetail() {
return "Iphone Details : Price 150000. Model 15 Pro";
}
}
@RestController
public class MAcBookController {
@GetMapping(path = "/mac/details")
public String getMacBookDetail() {
return "MAC Book Details : Price 200000. Model 2022";
}
@GetMapping(path = "/iphone/details")
public String getIphoneDetail() {
return "Iphone Details : Price 150000. Model 15 Pro";
}
}
@RequestBody Annotation:
The @RequestBody annotation in Spring is used to bind the HTTP request body to a
method parameter. This means that Spring will automatically deserialize the request body
into a Java object and that object is then passed to the method as a parameter. The
@RequestBody annotation can be used on controller methods.
@PostMapping("/users")
public User createUser(@RequestBody User user) {
// ...
}
➢ When you send a POST request to the /users endpoint with a JSON body containing the
user data, Spring will automatically deserialize the JSON into a User object and pass it to
the createUser() method.
➢ The @RequestBody annotation is a powerful tool that makes it easy to work with HTTP
request bodies in Spring. It is especially useful for developing REST APIs.
Here are some additional things to keep in mind about the @RequestBody annotation:
• The request body must be in a supported media type, such as JSON, XML.
• Spring will use an appropriate HTTP message converter to deserialize the request body.
• If the request body cannot be deserialized, Spring will throw
a HttpMessageNotReadableException.
Postman is a popular and widely used API (Application Programming Interface) testing
and development tool. It provides a user-friendly interface for sending HTTP requests to APIs
and inspecting the responses. Postman offers a range of features that make it valuable for
developers, testers, and anyone working with APIs:
• API client: Postman provides a powerful API client that allows you to send HTTP requests
to any API and inspect the responses. The API client supports a wide range of
authentication protocols and response formats.
Here are some examples of how Postman API Tools can be used:
• A developer can use Postman to explore a new API and learn how to use it.
• A QA engineer can use Postman to create and execute tests for an API.
• A DevOps engineer can use Postman to monitor an API for performance and availability
issues.
• A product manager can use Postman to generate documentation for an API.
• A sales engineer can use Postman to demonstrate an API to a customer.
Project Setup:
Requirement: Write a Rest Service for User Registration. User Details Should Be :
• User Name
• Email Id
• Mobile
• Password
{
"name" : "Dilip",
"email" : "dilip@gmail.com",
"mobile" : "+91 73777373",
"password" : "Dilip123"
}
package com.swiggy.user.request;
4. Now Create A controller and inside an endpoint for User Register Request Handling.
package com.swiggy.user.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.swiggy.user.request.UserRegisterRequest;
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/register")
public String getUserDetails(@RequestBody UserRegisterRequest request) {
System.out.println(request.getEmail());
System.out.println(request.getName());
System.out.println(request.getPassword());
return "User Created Successfully";
}
}
5. Deploy Your Application in Server Now. After Deployment we have to Test now weather it
Service is working or not.
o Open Postman
o Now Click on Add request
o Select Your Service HTTP method
o And Enter URL of Service
o Select Body
After Clicking on Send Button, Summited Request to Spring MVC REST Service
Endpoint method and we got Response back with 200 Ok status Code.
In Below, We can See in Server Console, Request Data is printed what we Received
from Client/Postman level as JSON data.
Examples:
URI with Template Path variables : /location/{locationName}/pincode/{pincode}
URI with Data replaced : /location/Hyderabad/pincode/500072
@GetMapping("/api/employees/{empId}")
public String getEmployeesById(@PathVariable(“empId”) String empId) {
In these kind of requirements, like getting Data with Resource ID’s. We can Use Path Variable
as part of URI instead of JSON mapping and equivalent Request Body classes. So Create a
REST endpoint with a Path Variable of Email ID.
➢ Now Add Method in Service Class for interacting with Repository Layer.
NOTE: We no need to define value inside @PathVariable when we are taking method
parameter name as it is URI template/Path variable.
Syntax : /{pathvar1}/{pathvar2}
Example: /pharmacy/{location}/pincode/{pincode}
After adding Orders, Please Get Order Details based on Email Id and Order Status.
In this case, we are passing values of Email ID and Order Status to find out Order Details. Now
we can take Path variables here to fulfil this requirement.
➢ Create an endpoints for adding Order Details and Getting Order Details with Email ID
and Order Status.
OrderRequest.java
➢ OrderResponse.java
package com.swiggy.order.response;
public OrderResponse() {
}
public OrderResponse(String orderID, String orderstatus, double amount,
String emailId, String city) {
this.orderID = orderID;
this.orderstatus = orderstatus;
this.amount = amount;
this.emailId = emailId;
this.city = city;
}
public String getOrderID() {
return orderID;
}
public void setOrderID(String orderID) {
this.orderID = orderID;
}
public String getOrderstatus() {
return orderstatus;
}
public void setOrderstatus(String orderstatus) {
this.orderstatus = orderstatus;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getCity() {
return city;
}
public void setCity(String city) {
package com.swiggy.order.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "swiggy_orders")
public class SwiggyOrders {
@Id
@Column
private String orderID;
@Column
private String orderstatus;
@Column
private double amount;
@Column
private String emailId;
@Column
private String city;
package com.swiggy.order.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.swiggy.order.request.OrderRequest;
import com.swiggy.order.response.OrderResponse;
import com.swiggy.order.service.OrderService;
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
OrderService orderService;
@PostMapping(value = "/create")
public String createOrder(@RequestBody OrderRequest request) {
return orderService.createOrder(request);
}
@GetMapping("/email/{emailId}/status/{status}")
public List<OrderResponse> getOrdersByemaailIDAndStaus(@PathVariable String
emailId, @PathVariable("status") String orderStaus ){
return orders;
}
}
package com.swiggy.order.service;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.swiggy.order.entity.SwiggyOrders;
import com.swiggy.order.repository.OrderRepository;
import com.swiggy.order.request.OrderRequest;
import com.swiggy.order.response.OrderResponse;
@Service
public class OrderService {
@Autowired
OrderRepository reposity;
return allOrders;
}
}
Add JPA Derived Query findBy() Method for Email Id and Order Status.
package com.swiggy.order.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.swiggy.order.entity.SwiggyOrders;
@Repository
public interface OrderRepository extends JpaRepository<SwiggyOrders, String>{
List<SwiggyOrders> findByEmailIdAndOrderstatus(String emailId, String orderStaus);
}
From Postman Test end point: URL formation, replacing Path variables with real values
@GetMapping("/pharmacy/{location}/pincode/{pincode}")
public String getPharmacyByLocationAndPincode(@PathVariable Map<String, String>
values) {
String location = values.get("location"); // Key is Path variable
String pincode = values.get("pincode");
return "Location Name : " + location + ", Pin code: " + pincode;
}
Query string is a part of a uniform resource locator (URL) that assigns values to
specified parameters. A query string commonly includes fields added to a base URL by a Web
browser or other client application. Let’s understand this statement in a simple way by an
example. Suppose we have filled out a form on websites and if we have noticed the URL
something like as shown below as follows:
http://internet.org/process-homepage?number1=23&number2=12
So in the above URL, the query string is whatever follows the question mark sign (“?”) i.e
(number1=23&number2=12) this part. And “number1=23”, “number2=12” are Query
Parameters which are joined by a connector “&”.
So in the above URL, the query string is “title=Query_string&action=edit” this part. And
“title=Query_string”, “action=edit” are Query Parameters which are joined by a connector
“&”.
Now we are discussing the concept of the query string and query parameter from the Spring
MVC point of view. Developing Spring MVC application and will understand how query strings
and query parameters are generated.
@RequestParam:
In Spring, we use @RequestParam annotation to extract the id of query parameters. Assume
we have Users Data, and we should get data based on email Id.
Requirement: Please Get User Details by using either email or mobile number
Method in controller:
@GetMapping("/details")
public List<Users> getUsersByEmailOrMobile(@RequestParam String email,
@RequestParam String mobileNumber) {
//Now we can pass Email Id and Mobile Number to service layer to fetch user details
List<Users> response = service.getUsersByEmailOrMobile(email, mobileNumber);
return response;
}
If we want to make sure any request parameter as optional, then we have to use attribute
required=false in side @RequestParam annotation. Now let’s make Request Parameter
mobileNumber as an Optional in controller.
@GetMapping("/details")
public List<Users> getUsersByEmailOrMobile(@RequestParam String email,
@RequestParam(required = false) String mobileNumber) {
Testing Endpoint: Now mobileNumber Request Parameter is missing in URI, but still our
endpoint is working only with one Request parameter email.
@GetMapping("/api")
@ResponseBody
public String getUsers(@RequestParam List<String> id) {
return "IDs are " + id;
}
URI: /api?id=1,2,3
URI : /api?id=1&id=2
We can also have multiple parameters without defining their names or count by just using
a Map:
Now we can read all Request Params from Map Object as Key and Value Pairs and we will
utilize as per requirement.
As a best practice, almost of developers are recommending following way. If you want
to identify a resource, you should use Path Variable. But if you want to sort or filter items on
data, then you should use query parameters. So, for example you can define like this:
“Swagger is a set of rules, specifications and tools that help us document our APIs.”
“By using Swagger UI to expose our API’s documentation, we can save significant
time.”
Swagger UI allows anyone — be it your development team or your end consumers — to
visualize and interact with the API’s resources without having any of the implementation logic in place.
It’s automatically generated from your OpenAPI (formerly known as Swagger) Specification, with the
visual documentation making it easy for back end implementation and client side consumption.
Swagger UI is one of the platform’s attractive tools. In order for documentation to be useful,
we will need it to be browsable and to be perfectly organized for easy access. It is for this reason that
writing good documentation may be tedious and use a lot of the developers’ time.
3. In Next Page, Add Spring Boot Modules/Starters as shown below and click on finish.
4. After Project Creation, Open pox.xml file and add below dependency starter in side
dependencies section and save.
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.1.0</version>
</dependency>
server.port=5566
server.servlet.context-path=/user
7. Enter URL in Browser for OpenAPI Swagger Documentation of Web services. Then you can
Swagger UI page with empty Services List. Because Our application not contained any web
services.
package com.tek.teacher.user.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
return response;
}
}
package com.tek.teacher.user.controller;
CreateUserResponse.java
package com.tek.teacher.user.controller;
Now Start Your Spring Boot App. After application started, Now please enter swagger URL in
browser. You can see all endpoints/services API request and response format Data.
In Spring Boot, whenever we create a new Spring Boot Application in spring starter, or inside
an IDE (Eclipse or STS) a file is located inside the src/main/resources folder named
as application.properties file.
In place of properties file, we can use YAML/YML based configuration files to achieve same
behaviour.
What is this YAML/YML file?
YAML stands for Yet Another Markup Language. YAML is a data serialization language
that is often used for writing configuration files. So YAML configuration file in Spring Boot
provides a very convenient syntax for storing logging configurations in a hierarchical format.
The application.properties file is not that readable. So most of the time developers choose
application.yml file over application.properties file. YAML is a superset of JSON, and as such
is a very convenient format for specifying hierarchical configuration data. YAML is more
readable and it is good for the developers to read/write configuration files.
• Comments can be identified with a pound or hash symbol (#). YAML does not support
multi-line comment, each line needs to be suffixed with the pound character.
• YAML files use a .yml or .yaml extension, and follow specific syntax rules.
If it is application.properties file :
server.port=4343
server.servlet.context-path=/gmail
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
Similarly, we can add all other Properties in same format always as per YAML scriprt rules
and regulations.
Now we can start our Spring Boot application as usual and continue development and
testing activities.
HTTP status codes are three-digit numbers that are returned by a web server in response to a
client's request made to a web page or resource. These codes indicate the outcome of the
request and provide information about the status of the communication between the client
(usually a web browser) and the server. They are an essential part of the HTTP (Hypertext
Transfer Protocol) protocol, which is used for transferring data over the internet. HTTP defines
these standard status codes that can be used to convey the results of a client’s request.
Some of HTTP status codes summary being used mostly in REST API creation
1xx Informational:
This series of status codes indicates informational content. This means that the
request is received and processing is going on. Here are the frequently used informational
status codes:
100 Continue:
This code indicates that the server has received the request header and the client can
now send the body content. In this case, the client first makes a request (with the Expect:
100-continue header) to check whether it can start with a partial request. The server can then
respond either with 100 Continue (OK) or 417 Expectation Failed (No) along with an
appropriate reason.
102 Processing:
2xx Success:
This series of status codes indicates the successful processing of requests. Some of the
frequently used status codes in this class are as follows.
200 OK:
This code indicates that the request is successful and the response content is returned
to the client as appropriate.
201 Created:
This code indicates that the request is successful and a new resource is created.
204 No Content:
This code indicates that the request is processed successfully, but there's no return
value for this request. For instance, you may find such status codes in response to the deletion
of a resource.
3xx Redirection:
This series of status codes indicates that the client needs to perform further actions
to logically end the request. A frequently used status code in this class is as follows.
403 Forbidden:
This code indicates that the server is refusing to respond to the request even if the
request is valid. The reason will be listed in the body content if the request is not a HEAD
method.
409 Conflict:
This code indicates that the request cannot be completed because it conflicts with
some rules established on resources, such as validation failure.
Generally we will have likewise below scenarios and respective status codes in REST API
services. For Example,
To bind response data and relevant HTTP status code with endpoint in side controller class,
we will use predefined Spring provided class ResponseEntity.
ResponseEntity:
ResponseEntity represents the whole HTTP response: status code, headers, and body.
As a result, we can use it to fully configure the HTTP response. If we want to use it, we have
to return it from the endpoint, Spring takes care of the rest. ResponseEntity is a generic type.
Consequently, we can use any type as the response body. This will be used in Controller
methods as well as in RestTemplate.
@RequestMapping("/handle")
public ResponseEntity<T> handle() {
// Logic
return new ResponseEntity<T>(ResponseData, ResponseHeaders, StatusCode);
}
Points to be noted:
@RestController
public class NetBankingController {
@PostMapping("/create")
@ResponseStatus(value = HttpStatus.CREATED) //Using Annotation
public String createAccount(@Valid @RequestBody AccountDetails accountDetails) {
@RestController
public class OrdersController {
@GetMapping("/orders")
public ResponseEntity<Order> getOrders(@RequestParam("orderID") String orderID) {
Order response = service.getOrders(orderID);
return new ResponseEntity<Order>( response, HttpStatus.OK);
}
}
This is how can write any Response Status code in REST API Service implementation.
Please refer RET API Guidelines for more information at what time which HTTP status code
should be returned to client.
HTTP headers can be classified into two main categories: request headers and response
headers.
Request Headers:
Request headers are included in an HTTP request sent by a client to a server. They provide
information about the client's preferences, the type of data being sent, authentication
credentials, and more. Some common request headers include:
Response Headers:
Response headers are included in an HTTP response sent by the server to the client. They
convey information about the server's response, the content being sent, caching directives,
and more. Some common response headers include:
• Content-Type: Specifies the format of the data in the response body.
• Content-Length: Specifies the size of the response body in bytes.
• Set-Cookie: Sets a cookie in the client's browser for managing state.
HTTP headers are important for various purposes, including negotiating content types,
enabling authentication, handling caching, managing sessions, and more. They allow both
clients and servers to exchange additional information beyond the basic request and response
data. Proper understanding and usage of HTTP headers are essential for building efficient and
secure web applications.
Spring MVC provides mechanisms to work with HTTP headers both in requests and responses.
Here's how you can work with HTTP headers in Spring MVC.
Accessing Request Headers: Spring provides the @RequestHeader annotation that allows
you to access specific request headers in your controller methods. You can use this annotation
as a method parameter to extract header values.
@GetMapping("/endpoint")
public ResponseEntity<String> handleRequest(@RequestHeader("Header-Name") String
headerValue) {
// Do something with the header and other values
➢ Header and its Value should come from Client while they are triggering this endpoint.
package com.flipkart.controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
@RestController
public class OrderController {
//Header is Part of Request, i.e. Should be Come from Client Side.
@GetMapping("/data")
public String testHeaders(@RequestHeader("user-name") String userName) {
return "Connected User : " + userName;
}
}
Testing: Without Sending Header and Value from Client, Sending Request to Service.
Result : We Got Bad request like Header is Missing i.e. Header is Mandatory by default if
we defined in Controller method.
Optional Headers:
If we want to make Header as an Optional i.e. non mandatory. we have to add an attribute
of required and Its value as false.
package com.flipkart.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OrderController {
package com.flipkart.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OrderController {
In Spring MVC, response headers can be set using the HttpServletResponse object or
the ResponseEntity class.
Here are some of the commonly used response headers in Spring MVC:
For example:
The ResponseEntity class is a more recent addition to Spring MVC. It provides a more concise
way to set headers, as well as other features such as status codes and body content. To set a
header using the ResponseEntity class, you can use the headers() method.
For example:
HttpHeaders:
In Spring MVC, the HttpHeaders class is provided by the framework as a convenient
way to manage HTTP headers in both request and response contexts. HttpHeaders is part of
the org.springframework.http package, and it provides methods to add, retrieve, and
manipulate HTTP headers. Here's how you can use the HttpHeaders class in Spring MVC:
In a Response:
You can use HttpHeaders to set custom headers in the HTTP response. This is often
done when you want to include specific headers in the response to provide additional
information to the client.
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OrderController {
Testing: Trigger endpoint from Client: Got Token and its value from Service in Headers.
If we are not handled exceptions then we will see Exception stack trace as shown in below at
HTTP client level as a response. As a Best Practice we should show meaningful Error Response
messages.
ControllerAdvice is an annotation in Spring and, as the name suggests, is “advice” for all
controllers. It enables the application of a single ExceptionHandler to multiple controllers.
With this annotation, we can define how to treat an exception in a single place, and the
system will call this exception handler method for thrown exceptions on classes covered by
this ControllerAdvice.
By using @ExceptionHandler and @ControllerAdvice, we’ll be able to define a central point
for treating exceptions and wrapping them in an Error object with the default Spring Boot
error-handling mechanism.
The first solution works at the @Controller level. We will define a method to handle
exceptions and annotate that with @ExceptionHandler i.e. We can define Exception Handler
Methods in side controller classes. This approach has a major drawback: The
@ExceptionHandler annotated method is only active for that particular Controller, not
globally for the entire application. But better practice is writing a separate controller advice
classes dedicatedly handle different exception at one place.
@RestController
public class FooController{
// Endpoint Methods
• It gives us full control over the body of the response as well as the status code.
• It provides mapping of several exceptions to the same method, to be handled together.
• It makes good use of the newer RESTful ResposeEntity response.
One thing to keep in our mind here is to match the exceptions declared
with @ExceptionHandler to the exception used as the argument of the method.
Example of Controller Advice class : Controller Advice With Exception Handler methods
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import jakarta.servlet.http.HttpServletRequest;
@ControllerAdvice
public class OrderControllerExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?>
handleMethodArgumentException(MethodArgumentNotValidException ex,
HttpServletRequest rq) {
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<?> handleNullpointerException(NullPointerException ex,
HttpServletRequest request) {
// Below Exception handler method will work for all child exceptions when we are not
//handled those specifically.
@ExceptionHandler(Exception.class)
public ResponseEntity<?> handleException(Exception ex, HttpServletRequest
request) {
• Now see How we are getting Error response with meaningful messages when Request
Body validation failed instead of complete Exception stack trace.
How it is working?
Whenever an exception occurred at controller layer due to any reason, immediately
controller will check for relevant exceptions handled as part of Exception Handler or not. If
handled, then that specific exception handler method will be executed and response will be
Which Exception takes Priority if we defined Child and Parent Exceptions Handlers?
From above example, if NullPointerException occurred then
handleNullpointerException() method will be executed even though we have logic for parent
Exception handling i.e. Priority given to child exception if we handled and that will be
returned as response data. Similarly we can define multiple controller advice classes with
different types of Exceptions along with relevant Http Response Status Codes.
consumes:
Using a consumes attribute to narrow the mapping by the content type. You can
declare a shared consumes attribute at the class level i.e. applicable to all controller
methods. Unlike most other request-mapping attributes, however, when used at the class
level, a method-level consumes attribute overrides rather than extends the class-level
declaration.
The consumes attribute also supports negation expressions — for example, !text/plain means
any content type other than text/plain.
Now let’s have an example, as below shown. Created an endpoint method, which accepts
only JSON data Request by providing consumes ="application/json".
@RequestMapping(path = "/add/model", consumes ="application/json",
method = RequestMethod.POST)
public String addLaptopDetails(@RequestBody LaptopDetails details) {
To support XML request Body, we should follow below configurations/steps. Spring boot, by
default, configures Jackson for parsing Java objects to JSON and converting JSON to Java
objects as part of REST API request-response handling. To accept XML requests and send XML
responses, there are two common approaches.
▪ Using Jackson XML Module
▪ Using JAXB Module
Start with adding Jackson’s XML module by including the jackson-dataformat-xml
dependency. Spring boot manages the library versions, so the following declaration is enough.
Add below both dependencies in POM.xml file of application.
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
Now we can define and access REST API Services with XML data format.
➢ Creating a service which accepts only XML Request Body i.e. endpoint accepts now only
XML request body but not JSON.
Create endpoint which supports both JSON and XML Request Body.
Below URI Request Mapping will support both XML and JSON Requests. We can pass multiple
data types consumes attribute with array of values.
consumes ={"application/json","application/xml"}
is equals to
consumes ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}
produces: with produces attributes, we can configure which type of Response data should
be generated from Response object.
Above endpoint generates only XML response for every incoming request.
Request for XML response: Add Header Accept and value as application/xml as shown.
Request for JSON response: Add Header Accept and value as application/json as shown.
Consuming REST services is nothing but integrating/calling other application REST API
services from our application logic.
For Example,
ICICI bank will produce API services to enable banking functionalities. Now Amazon
application integrated with ICICI REST services for performing Payment Options.
In This case:
Producer is : ICICI
Consumer is : Amazon
RestTemplate is used to create applications that consume RESTful Web Services. You can use
the exchange() or specific http methods to consume the web services for all HTTP methods.
Now we are trying to call Pharmacy Application API from our Spring Boot Application Flipkart
i.e. Flipkart consuming Pharmacy Application REST API.
{
"locationName": "hyderabad",
"conatcNumber": "323332323",
"pincode": 500099
}
Now assume we are receiving data from UI/Frontend to Flipkart application and that data we
are transferring to Pharmacy API with help of RestTemplate.
@RestController
@RequestMapping("/pharmacy")
public class PharmacyController {
@Autowired
PharmacyService pharmacyService;
@PostMapping("/add/location")
public String addPharmacyDetails(@RequestBody PharmacyLocation request) {
return pharmacyService.addPharmacyDetails(request);
}
}
➢ Now in Service class, we should write logic of integrating Pharmacy endpoint for adding
store details as per swagger notes.
➢ Crate a POJO class which is equal to JOSN Request payload of Pharmacy API call.
HttpEntity:
HttpEntity class is used to represent an HTTP request or response entity. It
encapsulates/binds the HTTP message's headers and body. You can use HttpEntity to
customize the headers and body of the HTTP request before sending it using RestTemplate. It
provides more control and flexibility over the request or response compared to simpler
methods like getForEntity(), postForObject(), etc.
➢ Now In service layer, Please map data from controller layer to API request body class.
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.flipkart.dto.PharmacyData;
import com.flipkart.pharmacy.request.PharmacyLocation;
@Service
public class PharmacyService {
➢ Now Test it from Postman and check pharmacy API call triggered or not i.e. check data is
inserted in DB or not from pharmacy application.
➢ Now create Request body as per our controller request body class.
{
"location": "pune",
"contact": "+918125262702",
"pincode": 500088
}
➢ Before executing from post man, please check DB data. In my table I have below data right
now.
➢ Request executed successfully and you got response from Pharmacy API of post REST API
call what we integrated. Verify In Database record inserted or not. It’s inserted.
When we are sending data to flipkart app, now flipkart app forwarded data to pharmacy
application via REST API call.
Now Let’s integrate Path variable and Query Parameters REST API Services:
Consuming API Services with Query Parameters:
Example1 : Consume below Service which contains Query String i.e. Query Parameters.
PharmacyResponse.java:
➢ Consume Below REST Service which contains Query Parameters From our Application.
package com.flipkart.service;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
Output:
{
"userName":"Suresh Singh",
"accountBalance":4040000.0,
"accountNumber":"122"
}
PharmacyResponse.java
return respone;
}
NOTE: We can handle both Path variable and Query Parameters of a single URI with Hashmap
Object. i.e. We are passing values to keys. Internally spring will replace values specifically.
➢ Example 3: We are Integrating one Real time API service from Online.
Above API call, Producing JSON Response, as shown in below Postman. Depends on Response
we should create JAVA POJO classes to serialize data from JAVA to JSON and vice versa.
➢ Based on API call Response, we should create Response POJO classes aligned to JSON
Payload.
Country.java
public class Country {
private String name;
private String iso2;
private int lat;
System.out.println(respone);
return respone;
}
In Spring's RestTemplate, we can work with HTTP headers by using the HttpHeaders
class. You can add, retrieve, and manipulate headers in both requests and responses. Here's
how we can work with headers in RestTemplate:
In this example, we create an HttpHeaders object and set custom headers. We can add
headers to your HTTP request before sending it using RestTemplate. Here's an example of how
to add headers to a request:
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
We can access response headers when you receive a response from the server. Here's
an example:
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
// Send a GET request and receive the entire ResponseEntity for the response
ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
In this example, we use responseEntity.getHeaders() to access the response headers and then
retrieve specific header values using responseHeaders.getFirst("Header-Name").
Working with headers allows you to customize your requests and process responses more
effectively in your RestTemplate interactions.
Each environment requires a setting that is specific to them. For example, in DEV, we do not
need to constantly check database consistency. Whereas in UAT and PROD, we need to.
In this demo application, we will see how to configure different databases at runtime based
on the specific environment by their respective profiles.
The solution would be to create more property files and add the "profile" name as the suffix
and configure Spring Boot to pick the appropriate properties based on the profile.
• application-dev.properties
• application-sit.properties
• application-uat.properties
Generally profile files will be created specific to Environments in projects. So we will configure
properties and value which are really related to that environment. For example, In Real time
Projects implementation, we will have different databases i.e. different database hostnames
, user name and passwords for different environments. We will define common properties
and values across all environments in side main application.properties file.
Now run application as SpringBoot or Java application, SpringBoot will load by default
properties of application.properties and loads configured profiles properties file application-
dev.properties file.
This is how we are running application with specific profile i.e. loading specific profiles
properties file.
Now, we are done with properties files. Let's configure in the Configuration classes to pick the
correct properties.
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
public class DbConfgiuration {
@Value("${db.hostName}")
String hostName;
@Value("${db.userName}")
String userName;
@Value("${db.password}")
String password;
@Profile("sit")
@Bean
public String getSitDBConnection() {
System.out.println("SIT Creating DB Connection");
System.out.println(hostName);
System.out.println(userName);
System.out.println(password);
return "SIT DB Connection Sccusessfu.";
}
@Profile("dev")
@Bean
public String getDevDBConnection() {
System.out.println("Creating DEV DB Connection");
System.out.println(hostName);
System.out.println(userName);
System.out.println(password);
How application knows that this is DEV or SIT profile? how do we do this?
We will use application.properties with property spring.profiles.active=<profile>
From here, Spring Boot will know which profile to pick. Let's run the application now!
We are not seeing any details of sit profile bean configuration i.e. skipped Bean creation
because active profile is dev.
Now Let’s change our active profile to sit and observe which Bean object created and which
are ignored by Spring.
SpringBoot Actuator:
In Spring Boot, an actuator is a set of endpoints that provides various production-
ready features to help monitor and manage your application. It exposes useful endpoints that
give insights into your application's health, metrics, environment, and more. Actuators are
essential for monitoring and managing your Spring Boot application in production
environments.
To enable the Spring Boot Actuator, you need to add the relevant dependencies to
your project. In most cases, you'll want to include the `spring-boot-starter-actuator`
dependency in your pom.xml (Maven) or build.gradle (Gradle) file.
For Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Actuator endpoints let you monitor and interact with your application. Spring Boot
includes a number of built-in endpoints and lets you add your own. For example, the health
endpoint provides basic application health information.
The built-in endpoints are auto-configured only when they are available. Most applications
choose exposure over HTTP, where the ID of the endpoint and a prefix of /actuator is mapped
to a URL. For example, by default, the health endpoint is mapped to /actuator/health
ID Description
beans Displays a complete list of all the Spring beans in your application.
health Shows application health information.
info Displays arbitrary application info.
loggers Shows and modifies the configuration of loggers in the application.
Exposing Endpoints:
By default, only the health endpoint is exposed. Since Endpoints may contain sensitive
information, you should carefully consider when to expose them. To change which endpoints
are exposed, use the following specific include and exclude properties:
Property
management.endpoints.web.exposure.exclude=<endpoint>,<endpoint>
management.endpoints.web.exposure.include=<endpoint>,<endpoint>
* can be used to select all endpoints. For example, to expose everything over HTTP except
the env and beans endpoints, use the following properties:
Properties:
management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env,beans
For security purposes, only the /health endpoint is exposed over HTTP by default. You can
use the management.endpoints.web.exposure.include property to configure the endpoints
that are exposed.
Similarly, http://localhost:8080/actuator/mappings
Thank you
Dilip Singh