0% found this document useful (0 votes)
4 views23 pages

UNIT V Springboot

The document provides an overview of developing web applications using REST APIs with Spring Boot, detailing its features, setup process, and project creation using Spring Tool Suite (STS) and Maven. It explains the concept of REST APIs, their advantages, and the steps to create a basic Spring Boot application, including necessary configurations in the pom.xml file. Additionally, it covers creating a simple GET API and running the application on an embedded Tomcat server.

Uploaded by

Mani
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)
4 views23 pages

UNIT V Springboot

The document provides an overview of developing web applications using REST APIs with Spring Boot, detailing its features, setup process, and project creation using Spring Tool Suite (STS) and Maven. It explains the concept of REST APIs, their advantages, and the steps to create a basic Spring Boot application, including necessary configurations in the pom.xml file. Additionally, it covers creating a simple GET API and running the application on an embedded Tomcat server.

Uploaded by

Mani
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

UNIT V Web Applications development with Rest APIs 9

Rest API development with spring boot, Spring boot project with STS/MAVEN, Controller and Rest
Controller annotations, RequestBody, ResponseBody annotations, Error handling with spring boot

What is Spring Boot

Spring Boot is a project that is built on the top of the Spring Framework. It provides an easier and
faster way to set up, configure, and run both simple and web-based applications.

An Application Programming Interface (API) establishes a connection between computers or


between computer programs (applications) by providing readily available codes and information
pipelines. It is a type of software interface that acts as a mediator among other pieces of software to
streamline the interaction with one other.

Owing to diverse application architectures, different types of APIs such as Program, Local,
Web, or REST APIs assist developers in building robust digital solutions.

Representational State Transfer, also known as REST, is basically a standardized Software


Architecture Style, or in simple words, a specific type of API used by the industry to establish a
connection between Client and Server. REST API is built to guide the development and design of
the World Wide Web’s architecture.

What is a REST API? An API, or application programming interface, is a set of rules that define how
applications or devices can connect to and communicate with each other. A REST API is an API that
conforms to the design principles of the REST, or Representational State Transfer Architectural style.

REST APIs provide a flexible, lightweight way of integrating computer applications. REST APIs are
a simple and standardized approach to communication, which means you don’t have to worry about
how to format your data, it’s all standardized and industry use.

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.

REST APIs are scalable as well, which means as your service scales, you don’t have to worry about
the growing complexity. You can easily make modifications to your data and keep track of that across
Clients and Servers. They support caching which ensures high performance in large part. This guide
will uncover essential knowledge and working principles behind Spring Boot REST APIs in the
upcoming sections.

What is JAVA Spring Boot?

Spring Boot is a Java-based framework used to create stand-alone, production-grade Spring-based


Applications with ease. There are two words here, Spring and Boot. Spring is a huge framework
that lets you write enterprise JAVA applications, and Boot is a bootstrap that lets you bootstrap a
Spring application from scratch. This is how it gets its name, Spring Boot.

A production-grade application is a top-quality software that works smoothly and can handle lots of
users. It is designed to be used in real-life situations and can handle high amounts of traffic without
any issues. These applications are reliable, secure, and built to perform well.

The Spring Boot features and Spring framework offers a robust, lightweight infrastructure for Java
applications. It simplifies enterprise Java development by providing a comprehensive programming
and configuration model for web and non-web application parts.

Key Features of Spring Boot

• Ability to create stand-alone Spring Applications and Microservices with minimal


configuration and setup.
• Can automatically configure Spring Libraries and third-party libraries as well.
• Access to powerful features such as Key Metrics, Health Checks, and Externalized
Configuration.
• Simplifies your build configuration by providing opinionated ‘starter’ dependencies.
• Requires no code generation or XML configuration.
• Build RESTful Web Services for enterprise applications with ease using Spring Boot REST
APIs.

Spring Tool Suite (STS) IDE

Spring Tool Suite is an IDE to develop Spring applications. It is an Eclipse-based development


environment. It provides a ready-to-use environment to implement, run, deploy, and debug the
application. It validates our application and provides quick fixes for the applications.

Installing STS

Step 1: Download Spring Tool Suite from [Link] Click on the platform which
you are using. In this tutorial, we are using the Windows platform.

Step 2: Extract the zip file and install the STS.


sts-bundle -> [Link] -> Double-click on the [Link].

Step 3: Spring Tool Suite 3 Launcher dialog box appears on the screen. Click on the Launch button.
You can change the Workspace if you want.

Step 4: It starts launching the STS.

Creating a Spring Boot Project Using Maven

The Spring Boot Maven Plugin provides Spring Boot support in Apache Maven. It allows you to
package executable jar or war archives, run Spring Boot applications, generate build information and
start your Spring Boot application prior to running integration tests.

We can also use Spring Tool Suite to create a Spring project, we will create a Maven
Project using STS.

Step 1: Open the Spring Tool Suite.

Step 2: Click on the File menu -> New -> Maven Project

It shows the New Maven Project wizard. Click on the Next button.
Step 3: Select the maven-archetype-quickstart and click on the Next button.

Step 4: Provide the Group Id and Artifact Id. We have provided Group Id [Link] and
Artifact Id spring-boot-example-sts. Now click on the Finish button.

When we click on the Finish button, it creates the project directory, as shown in the following image.
Step 5: Open the [Link] file. We found the following code that is by default.

[Link]

package [Link];
public class App
{
public static void main( String[] args )
{
[Link]( "Hello World!" );
}
}

The Maven project has a [Link] file which contains the following default configuration.

[Link]

<project xmlns="[Link] xmlns:xsi="[Link]


MLSchema-instance"
xsi:schemaLocation="[Link] [Link]
[Link]">
<modelVersion>4.0.0</modelVersion>
<groupId>[Link]</groupId>
<artifactId>spring-boot-example-sts</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-example-sts</name>
<url>[Link]
<properties>
<[Link]>UTF-8</[Link]>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

Step 6: Add Java version inside the <properties> tag.

<[Link]>1.8</[Link]>

Step 7: In order to make a Spring Boot Project, we need to configure it. So, we are adding spring
boot starter parent dependency in [Link] file. Parent is used to declare that our project is a child
to this parent project.

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>[Link]</version>
<type>pom</type>
</dependency>

Step 8: Add the spring-boot-starter-web dependency in [Link] file.

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>[Link]</version>
</dependency>
Note: When we add the dependencies in the pom file, it downloads the related jar file. We can see
the downloaded jar files in the Maven Dependencies folder of the project directory.

After adding all the dependencies, the [Link] file looks like the following:

[Link]

<project xmlns="[Link] xmlns:xsi="[Link]


ema-instance"
xsi:schemaLocation="[Link] [Link]
[Link]">
<modelVersion>4.0.0</modelVersion>
<groupId>[Link]</groupId>
<artifactId>spring-boot-example-sts</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-example-sts</name>
<url>[Link]
<properties>
<[Link]>UTF-8</[Link]>
<[Link]>1.8</[Link]>
</properties>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>[Link]</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>[Link]</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

Step 9: Create a class with the name SpringBootExampleSts in the package [Link].

Right-click on the package name -> New -> Class -> provide the class name -> Finish
Step 10: After creating the class file, call the static method run() of the SpringApplication class. In
the following code, we are calling the run() method and passing the class name as an argument.

1. [Link]([Link], args);

Step 11: Annotate the class by adding an annotation @SpringBootApplication.

@SpringBootApplication

A single @SpringBootApplication annotation is used to enable the following annotations:

o @EnableAutoConfiguration: It enables the Spring Boot auto-configuration mechanism.


o @ComponentScan: It scans the package where the application is located.
o @Configuration: It allows us to register extra beans in the context or import additional
configuration classes.

[Link]

package [Link];
import [Link];
import [Link];
@SpringBootApplication
public class SpringBootExampleSts
{
public static void main(String[] args)
{
[Link]([Link], args);
}
}

Step: Run the file [Link], as Java Application. It displays the following in
the consol

How to create a Spring Boot project in STS

1. How to create a Spring Boot Project in STS(Spring Tool Suite) IDE?


These are the following steps for creating a Spring Boot Project in STS(Spring Tool Suite) IDE:
1. Click on the File menu
2. Click on the New
3. Select Spring Starter Project
4. Enter the Project Name etc. and then click the Next Button
5. Select the Spring Boot Version and Select Dependency Library for the project.

6. Click on the Finish button then the project is successfully created.


2. Project Structure of Spring Boot Project
This image is shown the project structure of the Spring Boot project STS(Spring Tool Suite) IDE:

Maven Dependency
[Link]:

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>[Link]</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<[Link]>17</[Link]>
</properties>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>[Link]</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

SpringBootApplication class:

package [Link];
import [Link];
import [Link];
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
[Link]([Link], args);
}
}

2. How to run a Spring Boot Project in STS(Spring Tool Suite) IDE?


Right-click on this SpringBootAppliction class(automatically generated ) of this project then
click on Run As and then click on Java Application. Now the project is running successfully.
See the output console embedded tomcat server port 8080 is started.

How to create a basic application in Java Spring Boot

Spring MVC is a widely used module of spring which is used to create scalable web applications.
But the main disadvantage of spring projects is that configuration is really time-consuming and
can be a bit overwhelming for the new developers. Making the application production-ready takes
some time if you are new to the spring. The solution to this is Spring Boot. Spring Boot is built on
the top of the spring and contains all the features of spring. In this article, we will see how to
create a basic spring boot application.

Spring Initializr is a web-based tool using which we can easily generate the structure of the
Spring Boot project.
It also provides various different features for the projects expressed in a metadata model.
This model allows us to configure the list of dependencies which are supported by JVM. Here, we
will create the structure of an application using spring initializr and then use an IDE to create a
sample GET route. Therefore, to do this, the following steps are followed:

1. Go to Spring Initializr
2. Fill in the details as per the requirements. For this application:

Project: Maven
Language: Java
Spring Boot: 2.2.8
Packaging: JAR
Java: 8
Dependencies: Spring Web
1. Click on Generate which will download the starter project.
1. Extract the zip file. Now open a suitable IDE and then go to File->New->Project from existing
sources->Spring-boot-app and select [Link]. Click on import changes on prompt and wait
for the project to sync.
1. Note: In the Import Project for Maven window, make sure you choose the same version of
JDK which you selected while creating the project.
2. Go to src->main->java->[Link], create a java class with name
as Controller and add the annotation @RestController. Now create a GET API as shown
below:

@RestController

public class Controller {

// One syntax to implement a


// GET method

@GetMapping("/")

public String home()

{
String str
= "<html><body><font color=\"green\">"
+ "<h1>WELCOME To GeeksForGeeks</h1>"

+ "</font></body></html>";

return str;

// Another syntax to implement a


// GET method

@RequestMapping(

method = { [Link] },
value = { "/gfg" })

public String info()


{

String str2

= "<html><body><font color=\"green\">"

+ "<h2>GeeksForGeeks is a Computer"

+ " Science portal for Geeks. "


+ "This portal has been "
+ "created to provide well written, "

+ "well thought and well explained "

+ "solutions for selected questions."


+ "</h2></font></body></html>";

return str2;
}

}
1. This application is now ready to run. Run the SpringBootAppApplication class and wait for the
Tomcat server to start.

1. Note: The default port of the Tomcat server is 8080 and can be changed in
the [Link] file.
2. Now go to the browser and enter the URL localhost:8080. Observe the output and now do the
same for localhost:8080/gfg
What are the direct annotations for specifying HTTP methods in Spring?

The annotations are:

@GetMapping

@PostMapping

@PutMapping

@DeleteMapping

@PatchMapping

@GetMapping annotation is used for mapping HTTP GET requests onto specific handler methods.
It is composed annotation that acts as a shortcut for @RequestMapping(method=RequestMethod.
GET).

What is the @RestController annotation do?

It is a combination of the @Controller and @ResponseBody annotations. It is used to define the


RESTful web services and serves JSON, XML as well as custom responses.
@RestController
public class SamplController {
}
What are the main differences between @Controller and @RestController?

RequestBody, ResponseBody annotations:

@RequestBody and @ResponseBody annotations are used to bind the HTTP request/response body
with a domain object in the method parameter or return type. Behind the scenes, these annotation
uses HTTP Message converters to convert the body of HTTP request/response to domain objects.

@RequestBody Annotation
Annotation indicating a method parameter should be bound to the body of the web request. The body
of the request is passed through an HttpMessageConverter to resolve the method argument
depending on the content type of the request. Optionally, automatic validation can be applied by
annotating the argument with @Valid.
First, let’s have a look at a Spring controller method: In the below example, the employee JSON
object is converted into a Java employee object using @RequestBody annotation.

Spring automatically deserializes the JSON into a Java type assuming an appropriate one is specified.
By default, the type we annotate with the @RequestBody annotation must correspond to the JSON
sent from our client-side controller:
@ResponseBody Annotation

When you use the @ResponseBody annotation on a method, Spring converts the return value and
writes it to the HTTP response automatically. Each method in the Controller class must be annotated
with @ResponseBody.
Behind the Scenes
Spring has a list of HttpMessageConverters registered in the background. The responsibility of
the HTTPMessageConverter is to convert the request body to a specific class and back to the
response body again, depending on a predefined mime type. Every time an issued request
hits @ResponseBody, Spring loops through all registered HTTPMessageConverters seeking the first
that fits the given mime type and class and then uses it for the actual conversion.

The @ResponseBody annotation tells a controller that the object returned is automatically serialized
into JSON and passed back into the HttpResponse object.

Suppose we have a custom Response object:

Next, the associated controller can be implemented:


In the developer console of our browser or using a tool like Postman, we can see the following
response:
@RestController Annotation

Spring 4.0 introduced @RestController, a specialized version of the controller which is a


convenience annotation that does nothing more than adding
the @Controller and @ResponseBody annotations.

By annotating the controller class with @RestController annotation, you no longer need to add
@ResponseBody to all the request mapping methods. The @ResponseBody annotation is active by
default.

You might also like