0% found this document useful (0 votes)
153 views83 pages

Spring Boot Notes 1

The document is a comprehensive tutorial on Spring Boot, detailing its advantages, architecture, and comparison with Spring and Spring MVC. It introduces microservices and web services, explaining their functionalities and importance in application development. Additionally, it covers dependency management through Spring Boot starters and provides insights into annotations and configurations necessary for building Spring Boot applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
153 views83 pages

Spring Boot Notes 1

The document is a comprehensive tutorial on Spring Boot, detailing its advantages, architecture, and comparison with Spring and Spring MVC. It introduces microservices and web services, explaining their functionalities and importance in application development. Additionally, it covers dependency management through Spring Boot starters and provides insights into annotations and configurations necessary for building Spring Boot applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Spring Boot Tutorial

About the Trainer

• Name- Sagar Sarkar


• Years of experience- 5.7 Years
• Areas of expertise-Core Java ,Advance Java ,C#.NET, Java Web, Spring, Hibernate, Spring
Boot, Angular, React JS, Node JS, Express JS ,Quantitative Aptitude, SQL, Azure Cloud, R,
Tableau, Power BI , Python, Mathematics, Probability, Statistics, Data Science and
Machine Learning.
• Have provided Onsite training to associates at TCS Singapore and TCS Malaysia in
2022,2023 and 2025 in technologies such as Advance Java, Angular, JDBC, Java Web,
Spring, Hibernate, React JS ,Node JS, Express JS and Spring boot.
• Worked as Teaching Assistant in the Code In Place 2024 at Stanford University
• Also conducted overseas training in locations such as Australia, Thailand, Malaysia, Hong
Kong, and Singapore via online mode.
• Pursuing M.Tech(AI-ML) from IIT Madras .
• Gold Medalist in Academics in B.Tech (Mechanical and Automation Engineering) from
2015- 2019 at Amity University Noida.
• Worked as Summer Research Intern in Deep Learning at IIIT Allahabad.
• Selected in MTech (Computational Mechanics) at IIT Hyderabad and Post Graduate
Diploma in Applied Statistics Program at Indian Statistical Institute, Kolkata

Introduction to Spring Boot

• Spring Boot is an open source Java-based framework used to create a micro Service.
• It is developed by Pivotal Team and is used to build stand-alone and production ready
spring applications.
• Spring Boot provides a good platform for Java developers to develop a stand-alone and
production-grade spring application that you can just run.
• You can get started with minimum configurations without the need for an entire Spring
configuration setup.
• It can build standalone application.
• It can create production ready package.
• It has embedded Tomcat Server.
• It is convention over configuration model.

Advantages of Spring Boot

• To avoid complex XML configuration in Spring.


• To develop a production ready Spring applications in an easier way.
• To reduce the development time and run the application independently.
• Offer an easier way of getting started with the application.
• It provides a flexible way to configure Java Beans, XML configurations, and Database
Transactions.
• It provides a powerful batch processing and manages REST endpoints.
• In Spring Boot, everything is auto configured; no manual configurations are needed.
• It offers annotation-based spring application
• Eases dependency management
• It includes Embedded Servlet Container

Introduction to Microservices

• Micro Service is an architecture that allows the developers to develop and deploy
services independently.
• Each service running has its own process, and this achieves the lightweight model to
support business applications.
• Microservices are an architectural approach where a single application is composed of
many small, loosely coupled, and independently deployable components or services.
• Microservices are autonomous: Each microservice can be developed, deployed, and
operated independently without affecting other services.
• In a monolithic architecture, all processes run as a single service, tightly coupled.
• Microservices break down an application into independent components, each running
as a separate service.

Advantages of Microservices

• Simple scalability
• Compatible with Containers
• Minimum configuration
• Lesser production time
• Easy to understand and develop spring applications
• Increases productivity
• Reduces the development time

Spring Boot Architecture

• Spring Boot is a module of the Spring Framework.


• It is used to create stand-alone, production-grade Spring Based Applications with
minimum effort.
• It is developed on top of the core Spring Framework.
• Spring Boot follows a layered architecture in which each layer communicates with the
layer directly below or above (hierarchical structure) it.

The following are the types of Layers in Spring Boot Architecture:


• Presentation Layer: The presentation layer handles the HTTP requests, translates the
JSON parameter to object, and authenticates the request and transfer it to the business
layer. In short, it consists of views i.e., frontend part.
• Business Layer: The business layer handles all the business logic. It consists of service
classes and uses services provided by data access layers. It also performs authorization
and validation.
• Persistence Layer: The persistence layer contains all the storage logic and translates
business objects from and to database rows.
• Database Layer: In the database layer, CRUD (create, retrieve, update, delete) operations
are performed.

• Now we have validator classes, view classes, and utility classes.


• Spring Boot uses all the modules of Spring-like Spring MVC, Spring Data, etc. The
architecture of Spring Boot is the same as the architecture of Spring MVC, except for one
thing: there is no need for DAO and DAOImpl classes in Spring boot.
• Creates a data access layer and performs CRUD operation.
• The client makes the HTTP requests (PUT or GET).
• The request goes to the controller, and the controller maps that request and handles it.
After that, it calls the service logic if required.
• In the service layer, all the business logic is performed. It performs the logic on the data
that is mapped to JPA with model classes.
• A JSP page is returned to the user if no error occurred.
Spring vs Spring Boot

Spring Spring Boot

Spring Framework is a widely used Java Spring Boot Framework is widely used to
EE framework for building applications. develop REST APIs.

It aims to shorten the code length and


It aims to simplify Java EE development
provide the easiest way to develop Web
that makes developers more productive.
Applications.

The primary feature of Spring Boot is


The primary feature of the Spring Autoconfiguration. It automatically
Framework is dependency injection. configures the classes based on the
requirement.

It helps to make things simpler by allowing It helps to create a stand-alone


us to develop loosely coupled application with less configuration. (called
applications. Microservices)

The developer writes a lot of code


It reduces boilerplate code.
(boilerplate code) to do the minimal task.

To test the Spring project, we need to set Spring Boot offers embedded server such
up the server explicitly. as Jetty and Tomcat, etc.

It offers several plugins for working with an


It does not provide support for an in-
embedded and in-memory database such
memory database.
as H2.

Spring Boot comes with the concept of


Developers manually define dependencies starter in pom.xml file that internally takes
for the Spring project in pom.xml. care of downloading the dependencies
JARs based on Spring Boot Requirement.
Spring Boot vs Spring MVC

Spring Boot Spring MVC

Spring Boot is a module of Spring for Spring MVC is a model view controller-
packaging the Spring-based application based web framework under the Spring
with sensible defaults. framework.

It provides default configurations to build It provides ready to use features for


Spring-powered framework. building a web application.

There is no need to build configuration


It requires build configuration manually.
manually.

There is no requirement for a deployment


A Deployment descriptor is required.
descriptor.

It avoids boilerplate code and wraps


It specifies each dependency separately.
dependencies together in a single unit.

It reduces development time and


It takes more time to achieve the same.
increases productivity.

Spring Boot Starters

• Spring Boot starters are a set of predefined dependency descriptors which we


can include in our Spring Boot project.
• Each starter focuses on a specific area of functionality (e.g., web, data,
security, testing) and provides a curated set of related dependencies. By
adding a starter to your project, you automatically get all the required
libraries without having to hunt through documentation or sample code.
• To use a starter, simply add its corresponding dependency to your project’s
build configuration (Maven or Gradle).

Handling dependency management is a difficult task for big projects. Spring Boot
resolves this problem by providing a set of dependencies for developers
convenience.

For example, if you want to use Spring and JPA for database access, it is sufficient
if you include spring-boot-starter-data-jpa dependency in your project.
Note that all Spring Boot starters follow the same naming pattern spring-boot-
starter- *, where * indicates that it is a type of the application.

Examples

Look at the following Spring Boot starters explained below for a better
understanding −

Spring Boot Starter Security dependency is used for Spring Security. Its code is
shown below −

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

Spring Boot Starter web dependency is used to write a Rest Endpoints. Its code
is shown below −

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Spring Boot Starter Thyme Leaf dependency is used to create a web


application. Its code is shown below −

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Reference Link for Started Projects-

1.https://www.springboottutorial.com/spring-boot-starter-projects

2.https://www.tutorialspoint.com/spring_boot/spring_boot_starters.htm
Project in Starter Project

Spring Initializer Demo

• Src/main/java- it contains the main application file


• Src/test/java- it contains all the respective test cases of the application
• Application.properties- this file contains all the properties and configuration of the
respective application will be stored there.
• Pom.xml- The pom. xml file contains information of project and configuration
information for the maven to build the project such as dependencies, build
directory, source directory, test source directory, plugin, goals etc. Maven reads the
pom. xml file, then executes the goal.

Screenshot

Some Important Annotations


Spring Boot automatically configures your application based on the dependencies you
have added to the project by using @EnableAutoConfiguration annotation. For example,
if MySQL database is on your classpath, but you have not configured any database
connection, then Spring Boot auto-configures an in-memory database.

The entry point of the spring boot application is the class contains
@SpringBootApplication annotation and the main method.

Spring Boot automatically scans all the components included in the project by using
@ComponentScan annotation.

The entry point of the Spring Boot Application is the class contains
@SpringBootApplication annotation. This class should have the main method to
run the Spring Boot application. @SpringBootApplication annotation includes
Auto- Configuration, Component Scan, and Spring Boot Configuration.

You need to add @EnableAutoConfiguration annotation or @SpringBootApplication


annotation to your main class file. Then, your Spring Boot application will be automatically
configured.

Observe the following code for a better understanding −

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

@EnableAutoConfiguration
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

If you added @SpringBootApplication annotation to the class, you do not need to


add the @EnableAutoConfiguration, @ComponentScan and
@SpringBootConfiguration annotation. The @SpringBootApplication
annotation includes all other annotations.

Observe the following code for a better understanding −

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

Spring Boot application scans all the beans and package declarations when the
application initializes. You need to add the @ComponentScan annotation for your
class file to scan your components added in your project.

Observe the following code for a better understanding −

import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
We also need application.properties file to mention any configuration related details.

In spring we do a lot of XML configuration to implement the Dependency Injection. But in


Spring Boot , we can simply use annotation Autowired and component scan to achieve the
same.
Autowired- The @Autowired annotation marks a Constructor, Setter method, Properties
and Config() method as to be autowired that is ‘injecting beans'(Objects) at runtime by
Spring Dependency Injection mechanism
Here I am going to inject Class B into Class A, so we do not need any new operator here.
More on Autowired- https://www.geeksforgeeks.org/spring-autowired-annotation/

What are Web Services ?

A web service is a set of open protocols and standards that allow data to be exchanged
between different applications or systems.

Web services can be used by software programs written in a variety of programming


languages and running on a variety of platforms to exchange data via computer networks
such as the Internet in a similar way to inter-process communication on a single computer.
How does data exchange between applications?

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

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

In this way, regardless of the configuration of the machine, both can interact on the
common grounds of the data format.

XML Data Format

XML is a popular form as request and response in web services. Consider the following
XML code. The code shows that user has requested to access the Data Structure Course.
JSON(JavaScript Object Notation) format

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

Today, JSON is the universal standard of data exchange. It is found in every area of
programming, including front-end and server-side development, systems, middleware,
and databases.

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


platform-independent.

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

What is the Format of the Data then ?

Now a question arises, how does the Application A know the format of Request and
Response?
The answer to this question is "Service Definition." Every web service offers a service
definition. It is like a table of contents for every web service that an application offers.

Service definition specifies the following:

• Request/ Response format: Defines the request format made by consumer and
response format made by web service.
• Request Structure: Defines the structure of the request made by the application.
• Response Structure: Defines the structure of response returned by the web service.
• Endpoint: Defines where the services are available.

Web services have the following characteristics:

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

Loosely Coupled
A web service supports loosely coupled connections between systems. It communicates

by passing XML message to each other via a web API. Web API adds a layer of abstraction to

the environment that makes the connection adaptable and flexible.

Web Service is the set of rules or guidelines which enable communication among different
applications via the World wide web (.i.e. the internet).

Before web service, there were other technologies but some of them have dependencies
such as EJB (enterprise java bean) which allows applications to communicate only if the
applications are working on Java, these dependencies make communication difficult. These
dependencies are removed by web services.

In the present world, applications are developed on a variety of programming languages


such as Java, Python, PHP, etc.

These heterogeneous applications need communication to happen between them. Since


they are developed in different programming languages it becomes difficult to ensure
efficient communication between them. Here is where web services come into the picture,
web services provide a language-independent way of communication that means the
applications working on Java can communicate with other applications working on Python.
Therefore, web service helps us to invoke the functionality of other programs in the existing
program.

Why application needs to communicate

While working, some applications might need to use the service or functionality offered by
other applications. To use that service or functionality applications need to communicate
with each other.

Let us consider an example of a restaurant, when you visit the restaurant and ask for the
food(a service) then the waiter will be taking the order to the kitchen and serve you prepared
food from the kitchen. Here the waiter is like the web service which allows you(.i.e. client) to
communicate with the kitchen(.i.e. application).

The figure below shows another example of how the ICICI bank ATM used the service
provided by SBI bank to access the database of the customer which cannot be accessed by
the ICICI bank ATM directly.
How do web services work?

Web services use the request-response method to communicate among applications. For
any communication, we need a medium and a common format that can be understood by
everyone, in the case of web services medium is the internet and the common format is the
XML (Extensible Markup Language) format as every programming language can understand
the XML markup language.

Types of web services

There are mainly two types of web services:

1. SOAP web services: SOAP stands for Simple Object Access Protocol. These protocols
are based on XML which is a lightweight data exchange language. These protocols are
independent of language and can be run on any platform.

SOAP supports both stateful and stateless operations. Stateful means that the server keeps
track of the information received from the client on each request. While Stateless means
that each request contains enough information about the state of the client and thus server
does not need to bother about saving the state of the client thus increasing the speed of
communication.

Many companies such as IBM, Microsoft are producing an implementation of SOAP into their
systems.
2. RESTful web services: It stands for Representational State Transfer. They are also
language and platform-independent and are faster in comparison to SOAP. Nowadays
RESTful web services are more used than SOAP. They treat the data as resources. RESTful
web services return data in JSON format or XML format. These web services create the
object and send the state of the object in response to the client’s requests, that’s why known
as Representational State Transfer.

RESTful API

REST stands for REpresentational State Transfer. It is developed by Roy Thomas Fielding
who also developed HTTP.

The main goal of RESTful web services is to make web services more effective.

RESTful web services try to define services using the different concepts that are already
present in HTTP.

REST is an architectural approach, not a protocol.

We can build REST services with both XML and JSON. JSON is more popular format with
REST.

When we request a resource, we provide the representation of the resource. The important
methods of HTTP are:

SOAP API

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

SOAP: SOAP acronym for Simple Object Access Protocol.

It defines the standard XML format.

It also defines the way of building web services.


We use Web Service Definition Language (WSDL) to define the format of request XML and
the response XML.

FOR EXAMPLE :

Difference between RESTful and SOAP API

REST (Representational State Transfer) and SOAP (Simple Object Access Protocol) are the
most common methods for communication. These services enable the web to
communicate with the servers with HTTP protocol. REST is architectural style that works
over HTTP for communication while SOAP is a protocol with strict standards and is helpful
for complex system operations.

REST API
REST or Representational State Transfer is an architectural style for building the web
services. It is mostly used for lightweight and stateless communication. It uses simple
HTTP methods like GET, POST, PUT, and DELETE to perform operations on the data
resources.

Key Concepts

• Rest uses URI i.e. Uniform Resource Identifier and assume everything as a resource
• It do not store any past data, requests and do independent operations
• It relies on HTTP method to request any type of operation on the resource.
• Rest usually works with JSON and XML data formats.

SOAP API
SOAP or Simple Object Access Protocol is a messaging protocol. Is allows to exchange the
structure information without any platform. Soap uses the XML data fromat due to the
complexity. It is mostly used for complex systems with strict standards ensuring security
and reliability.

Key Concepts

• SOAP is a protocol as it has some strict rules for data fomat and communication.
• It manages the recods and maintain the state between the requests.
• SOAP relies on SSL and WS-Securiy for secured communication.
• SOAP works with the XML data format to handle the complex data.

Difference between SOAP API and REST API

SOAP API REST API

Relies on SOAP (Simple Object Relies on REST (Representational State


Access Protocol) Transfer) architecture using HTTP.

Generally transports data in JSON. It is based


Transports data in standard XML on URI. Because REST follows stateless model,
format. REST does not enforces message format as
XML or JSON etc.

Because it is XML based and relies


It works with GET, POST, PUT, DELETE
on SOAP, it works with WSDL

Works over HTTP, HTTPS, SMTP,


Works over HTTP and HTTPS
XMPP

Highly structured/typed Less structured -> less bulky data

Designed with large enterprise


Designed with mobile devices in mind
applications in mind

Terminologies of RESTful Webservices :

• Resources

Resources are just consistence mappings from an identifier [such as a URL path ] to some
set of views on server-side state.

Every resource must be uniquely addressable via a URI.

• Request and Response


The request is to a resource identified by a URI (URI = Unified Resource Identifier).

In this case, the resourse is "http://www.google.com".

Resources, or addressability is very important.

Every resourse is UL-addressable.

To change system state, simply change a resource.

URI example :

http://localhost:9999/restapi/books/{id}

GET – get the book whose id is provided.

POST – update the book whose id is provided.

DELETE - delete the book whose id Is provided.

http://localhost:9999/restapi/books

GET – get all books

Post – add a new book

REST technology is generally preferred to the more robust Simple Object Access Protocol
(SOAP) technology because REST uses less bandwidth, simple and flexible making it more
suitable for internet usage. It’s used to fetch or give some information from a web service.
All communication done via REST API uses only HTTP request.

Working: A request is sent from client to server in the form of a web URL as HTTP GET or
POST or PUT or DELETE request. After that, a response comes back from the server in the
form of a resource which can be anything like HTML, XML, Image, or JSON. But now JSON is
the most popular format being used in Web Services.
In HTTP there are five methods that are commonly used in a REST-based Architecture i.e.,
POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and
delete (or CRUD) operations respectively. There are other methods which are less
frequently used like OPTIONS and HEAD.

• GET: The HTTP GET method is used to read (or retrieve) a representation of a
resource. In the safe path, GET returns a representation in XML or JSON and an
HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT
FOUND) or 400 (BAD REQUEST).

• POST: The POST verb is most often utilized to create new resources. It’s used to
create subordinate resources. That is, subordinate to some other (e.g. parent)
resource. On successful creation, return HTTP status 201, returning a Location
header with a link to the newly created resource with the 201 HTTP status.
• PUT: It is used for updating the capabilities. However, PUT can also be used to
create a resource in the case where the resource ID is chosen by the client instead
of by the server. In other words, if the PUT is to a URI that contains the value of a
non-existent resource ID. On successful update, return 200 (or 204 if not returning
any content in the body) from a PUT. If using PUT for create, return HTTP status 201
on successful creation.
• PATCH: It is used to modify capabilities. The PATCH request only needs to contain
the changes to the resource, not the complete resource. This resembles PUT, but
the body contains a set of instructions describing how a resource currently residing
on the server should be modified to produce a new version. This means that the
PATCH body should not just be a modified part of the resource, but in some kind of
patch language like JSON Patch or XML Patch.
• DELETE: It is used to delete a resource identified by a URI. On successful deletion,
return HTTP status 200 (OK) along with a response body.

Request and Response

Now we will see how request and response work for different HTTP methods. Let’s assume
we have an API( https://www.geeksforgeeks.org/api/students ) for all students data of gfg.

• GET: Request for all Students.

Request
GET:/api/students

• POST: Request for Posting/Creating/Inserting Data

Request

POST:/api/students

{“name”:”Raj”}

• PUT or PATCH: Request for Updating Data at id=1

Request

PUT or PATCH:/api/students/1

{“name”:”Raj”}

• DELETE: Request for Deleting Data of id=1

Request

DELETE:/api/students/1

Sample HTTP Status codes returned in the response header


Rest API

Web Based APIs


SOAP APIs
Demo of a SOAP API- https://www.crcind.com/csp/samples/SOAP.Demo.cls

More on this -

1.https://www.boltic.io/blog/web-api-vs-rest-api

2.https://positiwise.com/blog/web-api-vs-rest-api

Project on Rest API:

1.Visit the Website- https://start.spring.io/

2.Do the configurations as mentioned in the Screenshot below:

Make sure that the version of Spring Boot is 3.3.4. Otherwise if not available ,kindly make
the changes in the pom.xml file. Kindly refer the screenshot below.
3.Also you need to add the following dependencies:

4.You can keep adding the dependencies according to the requirements by searching for
the dependency and clicking in explore.
5.You can copy paste the dependencies into the pom.xml file of your project

6.Click on the generate button in order to generate the Folder.

7.Unziip the folder and import it in the workspace of your Eclipse.

8.After you import the file, you might see a project architecture similar to the screenshot
attached below:

9. Once you import the file , you might experience some errors in the folder such as this:
10. You can resolve it with the help of the following steps:

-->Go to the pom.xml(Project Object Model) and replace all the http with https.

Screenshot is as follows:

-->Go to the C Drive->Users->Your Employee ID Folder->Open .m2 folder which gets


created when you import the Folder into the Project Folder. After that you can check your
Employee ID and India Domain password accordingly. Make sure that the Settings file is
according to the sample shared with you. Kindly update the local Repository Path with your
own Repository File path in .m2 folder in your Employee ID Folder. Also update your
Username and Password in the same settings.xml file.
Screenshot is as follows:

-->Right click on the Project, navigate to Maven and then select update Project. As
mentioned in the screenshot select the project and select the option for FORCE UPDATE
OF SNAPSHOT OR RELEASES:

11.Check and verify the contents of application.properties in the resources folder of the
same.
The settings done till now is common for all kinds of SpringBoot Projects , post this you can
do settings as per the specific requirements of the Project.

12.Now create a Controller Package and create a respective class for the same.

13. You can try out the respective sample code in order to implement a rest API Endpoint
@RestController- The @RestController annotation in Spring Boot is used to create RESTful
web services that return JSON or XML data:

Used to create controllers for REST APIs that return data, such as JSON or XML, rather than
a view . Maps request data to the defined request handler method , and converts the
response body to JSON or XML . Combines the functionality of the @Controller and
@ResponseBody annotations, so methods in a @RestController class do not need to be
annotated with @ResponseBody to return data to the client.

14. In this controller , we are calling a URL Mapping which will give me the ArrayList data
that is returning a list of strings.

15.In order to implement Swagger API that is to include order to include a Request
Dashboard by including the following dependency in pom.xml file.

16.The URL to accessed for Swagger API URL once you run the project is

http://localhost:PortNumber/swagger-ui/index.html

Kindly do a maven rebuild if you the link is giving you some issue.

17.Execute the Project by doing a right click on the main application file and running it as
Maven Build(Command-> spring-boot:run).

18.Then you can open the Swagger URL and test the request.
Indicates that your application is running.

Swagger UI will look something like this.

The underlying 200 OK Status means that API is configured correctly.

Click on the Execute Button


@RequestMapping – It is used to map HTTP requests to handler methods of MVC and REST
controllers.

@ResponseBody –It is used for binding a return value from a resource method to a web
response body. This is done by the use of HTTP message converters. This conversion
is done by looking at the content-type value in the HTTP request header.

Rest API Implementation using Spring Boot

Project on Rest API:

1.Visit the Website- https://start.spring.io/

2.Do the configurations as mentioned in the Screenshot below:

Make sure that the version of Spring Boot is 3.3.4. Otherwise if not available ,kindly make
the changes in the pom.xml file. Kindly refer the screenshot below.
3.Also, you need to add the following dependencies:

4.You can keep adding the dependencies according to the requirements by searching for
the dependency and clicking in explore.
5.You can copy paste the dependencies into the pom.xml file of your project

6.Click on the generate button in order to generate the Folder.

7.Unziip the folder and import it in the workspace of your Eclipse.

8.Add a Student Bean class under the main application package with the following code to
implement the bean class:

Use of Component Annotation-

@Component is an annotation that allows Spring to detect our custom beans


automatically.
In other words, without having to write any explicit code, Spring will:

• Scan our application for classes annotated with @Component


• Instantiate them and inject any specified dependencies into them
• Inject them wherever needed
9.Add a StudentController File in the package of com.example.ProjectName package as a
Java file named as StudentController with the following code:

Controller annotation-It is used to determine that it can return a response as a model and
view as well whereas the RestController annotation can return the response in the form of
XML,HTML,HTTP etc.

Response body annotation-

GetMapping Annotation- @GetMapping annotation in Spring is a powerful for building


RESTful web services. It maps HTTP GET requests to a specific handler method in Spring
controllers. With the help of @GetMapping annotation we can easily define endpoints of
RESTful API and handle various HTTP requests

RestController- RestController is used for making restful web services with the help of the
@RestController annotation. This annotation is used at the class level and allows the class
to handle the requests made by the client.

Make sure you include both the parametrized and non parametrized constructor in the
Student bean file.

10.After that right click on the project and run as Maven Build. You can mention spring-
boot:run as a part of Goals .

11. After the successful run, kindly hit the URL as http://localhost/getstudent in order to
demonstrate the get method without a DB in a sample format .Output is as follows:
12.As a part of Swagger API, you can hit the following URL

http://localhost:8080/swagger-ui/index.html

and check for the APi implementation .Screenshot is as follow:


200 Status means success. Swagger is very much UI friendly.

13. Now in out next example we will try to return a list of Students as a part of GetMapping.
You can add the following Code as a part of StudentController file.

You will see automatic changes in the console of the application because of Dev tool
dependency implementation.

14. After the successful run, kindly hit the URL as http://localhost/studentlist in order to
demonstrate the get method without a DB in a sample format. Output is as follows:

15. As a part of Swagger API, you can hit the following URL

http://localhost:8080/swagger-ui/index.html and check for the API implementation .

Screenshot is as follow:
16.We can also implement GetMapping as of form of Path Variable or URL Based
arguments as shown in the code snippet below:

Path Variable annotation

17. After the successful run, kindly hit the URL as


http://localhost:8080/students/3/Sagar/Sarkar which is a sample URL in order to
demonstrate the get method without a DB in a sample format. Output is as follows:
18. As a part of Swagger API, you can hit the following URL

http://localhost:8080/swagger-ui/index.html and check for the API implementation .

You can fill in the sample details and fetch it accordingly by clicking on execute button.
You can check the request URL and the corresponding response body afterwards. Refer
the screenshot:
Difference between pathVariable and requestparam-

PathVariable- The @PathVariable annotation is used to extract data from the URL
path. It allows you to define placeholders in your request mapping URL and bind those
placeholders to method parameters.

Requestparameter- @RequestParam annotation is used to extract data from the query


parameters in the request URL. Query parameters are the key-value pairs that appear
after the ? in a URL

More on this :https://www.geeksforgeeks.org/spring-boot-pathvariable-and-


requestparam-annotations/

19. We can also implement Get Mapping in form of Request Parameter or URL Based
arguments as shown in the code snippet below:
20. As a part of Swagger API, you can hit the following URL

http://localhost:8080/swagger-ui/index.html and check for the API implementation .


You can also copy and paste the Request URL on the browser to check for the URL
localhost implementation:

localhost:8080/students/query?id=4&firstName=TT&lastName=UU

21. We can also implement GetMapping in form of a method which takes up and returns
list of strings as shown in the code snippet below:

22. As a part of Swagger API, you can hit the following URL

http://localhost:8080/swagger-ui/index.html and check for the API implementation .


23. After the successful run, kindly hit the URL as
http://localhost:8080/Stringaddquery?s=TCS&s=CTS&s=CAP&s=Adobe or

http://localhost:8080/Stringaddquery?s=TCS,CTS,CAP,Adobe

which is a sample URL in order to demonstrate the get method without a DB in a sample
format.

Output is as follows:
24.In order to implement the Post Mapping ,we need to provide information in the form of
JSON which will be inserted into the Java Object using the method.

PostMapping annotation- @PostMapping annotation in Spring MVC framework is a


powerful tool for handling the HTTP POST requests in your RESTful web services

RequestBody annotation- @RequestBody is mainly used with CRUD Operations to read the
request body.

ResponseStatusAnnotation- The @ResponseStatus annotation simplifies this process by


allowing developers to easily link specific status codes to methods or exceptions.

Here you can change the Status from OK 200 to CREATED 201 as well using Response
Status annotation.

25. As a part of Swagger API, you can hit the following URL

http://localhost:8080/swagger-ui/index.html and check for the API implementation .


26. In order to implement the Put Mapping ,we need to Update the information which is
provided in the form of JSON and get it reflected in the Swagger Implementation

27. As a part of Swagger API, you can hit the following URL

http://localhost:8080/swagger-ui/index.html and check for the API implementation .


28. In order to implement the Delete Mapping ,we need to delete the information and send
back a String which is provided in the form of JSON and get it reflected in the Swagger
Implementation.

29. As a part of Swagger API, you can hit the following URL

http://localhost:8080/swagger-ui/index.html and check for the API implementation .


30. There are many ways to shorten our code .For example you can use an annotation
which will be useful to shorten the time to compose any of the URL.

In this each and every URL will be preceded by students1.

31. As a part of Swagger API, you can hit the following URL

http://localhost:8080/swagger-ui/index.html and check for the API implementation .


32.There is one more annotation which redefines the response that you are sending which
defines the whole HTTP Response. We can fully configure the http response using
EntityResponse annotation. The whole HTTP response which consists of Status Codes,
Response Headers and the Body. Please refer the screenshot:
33. As a part of Swagger API, you can hit the following URL

http://localhost:8080/swagger-ui/index.html and check for the API implementation .

Now this was all about creating the Endpoints. Now, we will see how to consume the
endpoints. This task is ideally done using RestTemplate Approach.
If you check the URL for both the URL, you will find the same content:
Configure JPA with SpringBoot

Spring Data JPA or JPA stands for Java Persistence API, so before looking into that, we
must know about ORM (Object Relation Mapping).

So ,Object relation mapping is simply the process of persisting any java object directly into
a database table. Usually, the name of the object being persisted becomes the name of
the table, and each field within that object becomes a column.

With the table setup, each row corresponds to a record in the application.

Hibernate is one example of ORM. In short, JPA is the interface while hibernate is the
implementation.
The java persistence API provides a specification for persisting, reading, and managing
data from your java object to your relational tables in the database.

JPA specifies the set of rules and guidelines for developing interfaces that follow
standards. Straight to the point: JPA is just guidelines to implement ORM and there is no
underlying code for the implementation. Spring Data JPA is part of the spring framework.

The goal of spring data repository abstraction is to significantly reduce the amount of
boilerplate code required to implement a data access layer for various persistence stores.
Spring Data JPA is not a JPA provider, it is a library/framework that adds an extra layer of
abstraction on the top of our JPA provider line Hibernate.

JpaRepository is a JPA (Java Persistence API) specific extension of Repository. It contains


the full API of CrudRepository and PagingAndSortingRepository . So it contains API for
basic CRUD operations and also API for pagination and sorting.

Syntax:

public interface JpaRepository<T,ID>


extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T>

Where:

• T: Domain type that repository manages (Generally the Entity/Model class name)
• ID: Type of the id of the entity that repository manages (Generally the wrapper class
of your @Id that is created inside the Entity/Model class)

More on JPA- https://www.geeksforgeeks.org/spring-boot-jparepository-with-example/

Project on JPA SpringBoot

1.Visit the Website- https://start.spring.io/

2.Do the configurations as mentioned in the Screenshot below:


Make sure that the version of Spring Boot is 3.3.4. Otherwise if not available ,kindly make
the changes in the pom.xml file. Kindly refer the screenshot below.

3.Also you need to add the following dependencies:


4.You can keep adding the dependencies according to the requirements by searching for
the dependency and clicking in explore.

5.You can copy paste the dependencies into the pom.xml file of your project

6.Click on the generate button in order to generate the Folder.

7.Unziip the folder and import it in the workspace of your Eclipse.

8.After you import the file, you might see a project architecture similar to the screenshot
attached below:
9. Once you import the file , you might experience some errors in the folder such as this:

10. You can resolve it with the help of the following steps:

-->Go to the pom.xml(Project Object Model) and replace all the http with https.

Screenshot is as follows:
-->Go to the C Drive->Users->Your Employee ID Folder->Open .m2 folder which gets
created when you import the Folder into the Project Folder. After that you can check your
Employee ID and India Domain password accordingly. Make sure that the Settings file is
according to the sample shared with you. Kindly update the local Repository Path with your
own Repository File path in .m2 folder in your Employee ID Folder. Also update your
Username and Password in the same settings.xml file.

Screenshot is as follows:
-->Right click on the Project, navigate to Maven and then select update Project. As
mentioned in the screenshot select the project and select the option for FORCE UPDATE
OF SNAPSHOT OR RELEASES:

11.Import it to the Workspace using Existing Maven Project, change the Spring boot version
to 3.3.4 and do the Maven update project to get it up to date.

12.Add a WebApp Custom folder in the resources folder and add a JSP Page.

Content of the Home.jsp will be as follows:


After that we need to add the respective dependency for tomcat jasper from Maven
repository site . For example for the current project the tomcat version is 10.1.30. Kindly
check it under Maven Dependency dropdown.

Similarly search the same as per the screenshot below:


Kindly add the dependency in the pom.xml file without which the we will not be able to
execute any jsp file.

For example dependency could be like this, ignore/include the version part as per the
version compatibility.

Link- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper/10.1.30

13.Create a Controller class to handle the inputs given by the user under the same
package as of com.example.JSPDemo .This is going to access the JSP.

Write the following Code

14.In application.properties kindly do the necessary configurations:


Also, JPA based configurations are needed as JPA shows us how the interaction takes
place between the DB and Java Objects. We use h2 as a database which is a kind of In
Memory DB.

15. Next we are going to create our Entity File which will be the basis of Model.

16.Now Create a Java File named as EmpRepository which will be extending the class of
JpaRepository

Do a right click +CTRL on the JpaRepository , then you can see all the available functions
under JPA In-Built Library.
17.You can also login into the h2 Console on your browser with the help of the following
URL

https://localhost:8080/h2-console

You need to enter the credentials as per the application.properties file. You will find the
screen similar to the below screenshot.Test the connection once.

18.Upon connecting to the DB. You will find a screen similar to the one below:
19.Now you can Maven Build your application, you can try hitting the URL

https://localhost/8080/home

As home URL is mapped to home.jsp page so the below page will be loaded:

Upon filling the details, when we hit the submit button, then it will invoke /addemp URL
from controller, which will be saving the data into the DB as mentioned in the code
We can also fetch all the Data using Dao File inbuilt functions such as findAll for the
Datapoints to be displayed etc. You can check that in the Console.

Later you can go to the h2 console and run a Select query to check the data

As you can see, once we log out of the h2 console, we lost the old data because of it being
a in Memory Database.
API 1-

API 2-

API 3- In case Rest Controller is implemented


API 3- In case Controller is implemented
In case of Controller, we cannot directly access the endpoints , that is possible only in
case of RestController.

DTO (Data Transfer Objects)


Data Transfer Object Design Pattern is a frequently used design pattern. It is basically used
to pass data with multiple attributes in one shot from client to server, to avoid multiple
calls to a remote server.

There are many reasons why we use DTO's such as Instead of sending single entity as REST
API response to client, we can use DTO to combine and return multiple entities or multiple
attributes in one shot from server to client.

Project on DTO:

1.Visit the Website- https://start.spring.io/

2.Do the configurations as mentioned in the Screenshot below:


Make sure that the version of Spring Boot is 3.3.8. Otherwise if not available ,kindly make
the changes in the pom.xml file. Kindly refer the screenshot below.

3.Also you need to add the following dependencies:


4.You can keep adding the dependencies according to the requirements by searching for
the dependency and clicking in explore.

5.You can copy paste the dependencies into the pom.xml file of your project

6.Click on the generate button in order to generate the Folder.

7.Unziip the folder and import it in the workspace of your Eclipse.

8.After you import the file, you might see a project architecture similar to the screenshot
attached below:
9. Once you import the file , you might experience some errors in the folder such as this:

10. You can resolve it with the help of the following steps:

-->Go to the pom.xml(Project Object Model) and replace all the http with https.

Screenshot is as follows:
-->Go to the C Drive->Users->Your Employee ID Folder->Open .m2 folder which gets
created when you import the Folder into the Project Folder. After that you can check your
Employee ID and India Domain password accordingly. Make sure that the Settings file is
according to the sample shared with you. Kindly update the local Repository Path with your
own Repository File path in .m2 folder in your Employee ID Folder. Also update your
Username and Password in the same settings.xml file.

Screenshot is as follows:
-->Right click on the Project, navigate to Maven and then select update Project. As
mentioned in the screenshot select the project and select the option for FORCE UPDATE
OF SNAPSHOT OR RELEASES:

11.Check and verify the contents of application.properties in the resources folder of the
same.

The settings done till now is common for all kinds of Spring Boot Projects , post this you
can do settings as per the specific requirements of the Project. Because we are trying to
implement DTO, so we need to use the lombok dependency import which will be used to
include the annotations used for DTO.

Also do one last project setting by opening the properties of the project and enable the
Project Specific Settings under the Java Compiler tab.Please make sure , you import
lombok jar file which will be helpful for Entity Class annotation mapping
12. Create the Entity file in the SpringBoot application package:(Code is shown in the
package)

Now no need to getter and setter as we are using lombok for automatic generation of getter
and setter.

13. Now we will be writing the Repository file to implement JPA related functions.

Now , we are done with the DB configuration.

14. Now we need to create the controller for endpoints. We are going to create a service
layer, controller, entity and a repository layer.

Now I will be using Dto in order to perform CRUD in the table not in the form of Post but in
the form of DTO Objects which are more secure and do not expose the information.

More about DTO Pattern- https://www.baeldung.com/java-dto-pattern

First the service class is created and then methods are implemented in the Post Service
Implementation.

Client--> Endpoints in Controller-->Service Layer is connected-->Service Layer


Implementation is called-->Repository methods are called -->Data is returned from
the Table-->Post Object will be returned to the service layer -->Controller-->Swagger
API.
15.Create a service class which will define the methods that will be implemented.

Now write the implementation layer.

16.Now in controller we can have our required for each functionality.


We have to make use of DTOs when it comes to large project and implementation.

Exception Handling

Exception handling in Spring Boot helps to deal with errors and exceptions present in APIs,
delivering a robust enterprise application. This article covers various ways in which
exceptions can be handled and how to return meaningful error responses to the client in a
Spring Boot Project. To create a user defined exception. For that we will create a class with
run time exception.

Find the Exception file being included in the last project.


Execute the Project in order to test the functionality. Check the Swagger URL to check for
the Rest API Endpoints. Keep the h2 db console and the swagger API Console.

API 1-
API 2-
API 3-
API 4-
API 5-

You might also like