0% found this document useful (0 votes)
2 views21 pages

Introduction to RESTful Web Services

Spring Boot is a module of the Spring Framework that simplifies the setup and development of stand-alone applications with minimal configuration. It eliminates the need for XML configuration and supports rapid application development through features like embedded servers and dependency management. Additionally, Spring Boot integrates with various Spring projects to enhance functionality, making it suitable for modern application development.

Uploaded by

tiwarinitish960
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views21 pages

Introduction to RESTful Web Services

Spring Boot is a module of the Spring Framework that simplifies the setup and development of stand-alone applications with minimal configuration. It eliminates the need for XML configuration and supports rapid application development through features like embedded servers and dependency management. Additionally, Spring Boot integrates with various Spring projects to enhance functionality, making it suitable for modern application development.

Uploaded by

tiwarinitish960
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 21

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.

It is a Spring module that provides the RAD (Rapid Application


Development) feature to the Spring Framework. It is used to create a
stand-alone Spring-based application that you can just run because it
needs minimal Spring configuration.

In short, Spring Boot is the combination of Spring


Framework and Embedded Servers.

In Spring Boot, there is no requirement for XML configuration (deployment


descriptor). It uses convention over configuration software design
paradigm that means it decreases the effort of the developer.

We can use Spring STS IDE or Spring Initializr to develop Spring Boot
Java applications.

Why should we use Spring Boot Framework?

We should use Spring Boot Framework because:

o The dependency injection approach is used in Spring Boot.


o It contains powerful database transaction management capabilities.
o It simplifies integration with other Java frameworks like
JPA/Hibernate ORM, Struts, etc.
o It reduces the cost and development time of the application.

Along with the Spring Boot Framework, many other Spring sister projects
help to build applications addressing modern business needs. There are
the following Spring sister projects are as follows:
o Spring Data: It simplifies data access from the relational
and NoSQL databases.
o Spring Batch: It provides powerful batch processing.
o Spring Security: It is a security framework that provides
robust security to applications.
o Spring Social: It supports integration with social networking like
LinkedIn.
o Spring Integration: It is an implementation of Enterprise
Integration Patterns. It facilitates integration with other enterprise
applications using lightweight messaging and declarative
adapters.

Advantages of Spring Boot


o It creates stand-alone Spring applications that can be started using
Java -jar.
o It tests web applications easily with the help of
different Embedded HTTP servers such as Tomcat, Jetty, etc. We
don't need to deploy WAR files.
o It provides opinionated 'starter' POMs to simplify our Maven
configuration.
o It provides production-ready features such as metrics, health
checks, and externalized configuration.
o There is no requirement for XML configuration.
o It offers a CLI tool for developing and testing the Spring Boot
application.
o It offers the number of plug-ins.
o It also minimizes writing multiple boilerplate codes (the code that
has to be included in many places with little or no alteration), XML
configuration, and annotations.
o It increases productivity and reduces development time.

Limitations of Spring Boot


Spring Boot can use dependencies that are not going to be used in the
application. These dependencies increase the size of the application.

Goals of Spring Boot


The main goal of Spring Boot is to reduce development, unit
test, and integration test time.

o Provides Opinionated Development approach


o Avoids defining more Annotation Configuration
o Avoids writing lots of import statements
o Avoids XML Configuration.

By providing or avoiding the above points, Spring Boot Framework


reduces Development time, Developer Effort, and increases
productivity.

Prerequisite of Spring Boot


To create a Spring Boot application, following are the prerequisites. In this
tutorial, we will use Spring Tool Suite (STS) IDE.

o Java 1.8
o Maven 3.0+
o Spring Framework 5.0.0.BUILD-SNAPSHOT
o An IDE (Spring Tool Suite) is recommended.

Spring Boot Features


o Web Development
o SpringApplication
o Application events and listeners
o Admin features
o Externalized Configuration
o Properties Files
o YAML Support
o Type-safe Configuration
o Logging
o Security

Web Development

It is a well-suited Spring module for web application development. We can


easily create a self-contained HTTP application that uses embedded
servers like Tomcat, Jetty, or Undertow. We can use the spring-boot-
starter-web module to start and run the application quickly.
SpringApplication

The SpringApplication is a class that provides a convenient way to


bootstrap a Spring application. It can be started from the main method.
We can call the application just by calling a static run() method.

1. public static void main(String[] args)


2. {
3. SpringApplication.run(ClassName.class, args);
4. }

Application Events and Listeners

Spring Boot uses events to handle the variety of tasks. It allows us to


create factories file that is used to add listeners. We can refer it to using
the ApplicationListener key.

Always create factories file in META-INF folder


like META-INF/spring.factories.

Admin Support

Spring Boot provides the facility to enable admin-related features for the
application. It is used to access and manage applications remotely. We
can enable it in the Spring Boot application by
using spring.application.admin.enabled property.

Externalized Configuration

Spring Boot allows us to externalize our configuration so that we can work


with the same application in different environments. The application uses
YAML files to externalize configuration.

Properties Files

Spring Boot provides a rich set of Application Properties. So, we can


use that in the properties file of our project. The properties file is used to
set properties like server-port =8082 and many others. It helps to
organize application properties.

YAML Support

It provides a convenient way of specifying the hierarchical configuration. It


is a superset of JSON. The SpringApplication class automatically supports
YAML. It is an alternative of properties file.

Type-safe Configuration
The strong type-safe configuration is provided to govern and validate the
configuration of the application. Application configuration is always a
crucial task which should be type-safe. We can also use annotation
provided by this library.

Logging

Spring Boot uses Common logging for all internal logging. Logging
dependencies are managed by default. We should not change logging
dependencies if no customization is needed.

Security

Spring Boot applications are spring bases web applications. So, it is secure
by default with basic authentication on all HTTP endpoints. A rich set of
Endpoints is available to develop a secure Spring Boot application.

Prerequisite
Before learning Spring Boot, you must have the basic knowledge of Spring
Framework.

Audience
Our Spring Boot Tutorial is designed to help beginners and professionals.

Problem
We assure you that you will not find any problem with the Spring Boot
Tutorial. But if there is any mistake, please post the problem in the
contact form.

Introduction to RESTful Web Services


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

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

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

o GET: It reads a resource.


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

For example, if we want to perform the following actions in the social


media application, we get the corresponding results.

POST /users: It creates a user.

GET /users/{id}: It retrieves the detail of a user.

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

DELETE /users: It deletes all users.

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

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

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

Further, we will implement these URI in our project.

HTTP also defines the following standard status code:

o 404: RESOURCE NOT FOUND


o 200: SUCCESS
o 201: CREATED
o 401: UNAUTHORIZED
o 500: SERVER ERROR

RESTful Service Constraints

o There must be a service producer and service consumer.


o The service is stateless.
o The service result must be cacheable.
o The interface is uniform and exposing resources.
o The service should assume a layered architecture.

Advantages of RESTful web services

o RESTful web services are platform-independent.


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

Spring vs. Spring Boot vs. Spring MVC


Spring vs. Spring Boot
Spring: Spring Framework is the most popular application development
framework of Java. The main feature of the Spring Framework
is dependency Injection or Inversion of Control (IoC). With the help of
Spring Framework, we can develop a loosely coupled application. It is
better to use if application type or characteristics are purely defined.

Spring Boot: Spring Boot is a module of Spring Framework. It allows us


to build a stand-alone application with minimal or zero configurations. It is
better to use if we want to develop a simple Spring-based application or
RESTful services.

The primary comparison between Spring and Spring Boot are discussed
below:

Spring Spring Boot

Spring Framework is a widely Spring Boot Framework is widely used to


used Java EE framework for develop REST APIs.
building applications.

It aims to simplify Java EE It aims to shorten the code length and provide
development that makes the easiest way to develop Web Applications.
developers more productive.
The primary feature of the The primary feature of Spring Boot
Spring Framework is Autoconfiguration. It automatically
is dependency injection. configures the classes based on the requirement.

It helps to make things simpler It helps to create a stand-alone application with


by allowing us to less configuration.
develop loosely
coupled applications.

The developer writes a lot of It reduces boilerplate code.


code (boilerplate code) to do
the minimal task.

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

It does not provide support for It offers several plugins for working with an
an in-memory database. embedded and in-memory database such
as H2.

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

Spring Boot vs. Spring MVC


Spring Boot: Spring Boot makes it easy to quickly bootstrap and start
developing a Spring-based application. It avoids a lot of boilerplate code.
It hides a lot of complexity behind the scene so that the developer can
quickly get started and develop Spring-based applications easily.

Spring MVC: Spring MVC is a Web MVC Framework for building web
applications. It contains a lot of configuration files for various capabilities.
It is an HTTP oriented web application development framework.

Spring Boot and Spring MVC exist for different purposes. The primary
comparison between Spring Boot and Spring MVC are discussed below:

Spring Boot Spring MVC

Spring Boot is a module of Spring for Spring MVC is a model view


packaging the Spring-based application with controller-based web framework
sensible defaults. under the Spring framework.

It provides default configurations to It provides ready to use features


build Spring-powered framework. for 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


descriptor. is required.

It avoids boilerplate code and wraps It specifies each dependency


dependencies together in a single unit. separately.

It reduces development time and increases It takes more time to achieve the
productivity. same.

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
efforts. 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.
Before understanding the Spring Boot Architecture, we must know the
different layers and classes present in it. There are four layers in Spring
Boot are as follows:

ADVERTISEMENT

o Presentation Layer
o Business Layer
o Persistence Layer
o Database Layer

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.
Spring Boot Flow Architecture

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


o 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 one thing: there is no need
for DAO and DAOImpl classes in Spring boot.
o Creates a data access layer and performs CRUD operation.
o The client makes the HTTP requests (PUT or GET).
o The request goes to the controller, and the controller maps that
request and handles it. After that, it calls the service logic if
required.
o In the service layer, all the business logic performs. It performs the
logic on the data that is mapped to JPA with model classes.
o A JSP page is returned to the user if no error occurred.

Initializing a RESTful Web Services Project


with Spring Boot
Step 1: Download the Spring Tool Suite
(STS) from https://spring.io/tools3/sts/all and extract it.

Step 2: Launch the STS.

Step 3: Click on File menu -> New -> Spring Starter Project ->

If the Spring Starter Project is not enlisted, then click on Other at the
bottom of the menu. A dialog box appears on the screen. Type Spring
Starter Project in the Wizards text box and click on the Next button.

Step 4: provide the name, group, and package of the project. We have
provided:

Name: restful-web-services

Group: com.javatpoint

Package: com.javatpoint.server.main

Click on the Next button.


Step 5: Choose the Spring Boot Version 2.1.8.
Step 6: We can see the project structure in the project explorer window.

Step 7: Go to the Maven Repository https://mvnrepository.com/ and


add Spring Web MVC, Spring Boot DevTools,
JPA, and H2 dependencies in the pom.xml. After adding the
dependencies, the pom.xml file looks like the following:
pom.xml

1. <project xmlns="http://maven.apache.org/POM/4.0.0"
2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
4. http://maven.apache.org/xsd/maven-4.0.0.xsd">
5. <modelVersion>4.0.0</modelVersion>
6. <parent>
7. <groupId>org.springframework.boot</groupId>
8. <artifactId>spring-boot-starter-parent</artifactId>
9. <version>2.1.8.RELEASE</version>
10. <relativePath/> <!-- lookup parent from repository -->
11. </parent>
12. <groupId>com.javatpoint</groupId>
13. <artifactId>restful-web-services</artifactId>
14. <version>0.0.1-SNAPSHOT</version>
15. <name>restful-web-services</name>
16. <description>Demo project for Spring Boot</description>
17. <properties>
18. <java.version>1.8</java.version>
19. </properties>
20. <dependencies>
21. <dependency>
22. <groupId>org.springframework.boot</groupId>
23. <artifactId>spring-boot-starter</artifactId>
24. </dependency>
25. <dependency>
26. <groupId>org.springframework.boot</groupId>
27. <artifactId>spring-boot-starter-activemq</artifactId>
28. </dependency>
29. <dependency>
30. <groupId>org.springframework.boot</groupId>
31. <artifactId>spring-boot-starter-web</artifactId>
32. </dependency>
33. <dependency>
34. <groupId>org.springframework.boot</groupId>
35. <artifactId>spring-boot-starter-tomcat</artifactId>
36. </dependency>
37. <dependency>
38. <groupId>org.springframework</groupId>
39. <artifactId>spring-webmvc</artifactId>
40. </dependency>
41. <!-- https://mvnrepository.com/artifact/
org.springframework.boot/spring-boot-devtools -->
42. <dependency>
43. <groupId>org.springframework.boot</groupId>
44. <artifactId>spring-boot-devtools</artifactId>
45. <scope>runtime</scope>
46. </dependency>
47. <!-- https://mvnrepository.com/artifact/
org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
48. <dependency>
49. <groupId>org.hibernate.javax.persistence</groupId>
50. <artifactId>hibernate-jpa-2.1-api</artifactId>
51. <version>1.0.0.Final</version>
52. </dependency>
53. <!-- https://mvnrepository.com/artifact/com.h2database/h2 --
>
54. <dependency>
55. <groupId>com.h2database</groupId>
56. <artifactId>h2</artifactId>
57. <scope>runtime</scope>
58. </dependency>
59. <dependency>
60. <groupId>org.apache.maven</groupId>
61. <artifactId>maven-archiver</artifactId>
62. <version>2.5</version>
63. </dependency>
64. <dependency>
65. <groupId>org.springframework.boot</groupId>
66. <artifactId>spring-boot-starter-test</artifactId>
67. <scope>test</scope>
68. </dependency>
69. </dependencies>
70. <build>
71. <plugins>
72. <plugin>
73. <groupId>org.springframework.boot</groupId>
74. <artifactId>spring-boot-maven-plugin</artifactId>
75. </plugin>
76. </plugins>
77. </build>
78. </project>

Step 8: Now open the RestfulWebServicesApplication.java file and


Run the file as Java Application.

1. package com.javatpoint.server.main;
2. import org.springframework.boot.SpringApplication;
3. import org.springframework.boot.autoconfigure.SpringBootApplicati
on;
4. @SpringBootApplication
5. public class RestfulWebServicesApplication
6. {
7. public static void main(String[] args)
8. {
9. SpringApplication.run(RestfulWebServicesApplication.class, args);
10. }
11. }

It does not perform any service but ensures that the application is running
properly.

Output

Creating a Hello World Service


Step 1: Create a new class with the name HelloWorldController in the
package com.javatpoint.server.main.
Step 2: Whenever we create a web service, we need to define two
things Get method and the URI. Now create the helloWorld() method
which returns the string "Hello World." If we want to tell the spring MVC
that it is going to handle the REST request, we have to
add @RestController annotation. Now it becomes a rest controller which
can handle the Rest request.

The next thing we have to do is create a mapping for the method.


Add @RequestMapping annotation just above the helloWorld() method.
The HelloWorldController looks like the following:

1. package com.javatpoint.server.main;
2. import org.springframework.web.bind.annotation.RequestMapping;
3. import org.springframework.web.bind.annotation.RequestMethod;
4. import org.springframework.web.bind.annotation.RestController;
5. //Controller
6. @RestController
7. public class HelloWorldController
8. {
9. //using get method and hello-world as URI
10. @RequestMapping(method=RequestMethod.GET, path="/
hello-world")
11. public String helloWorld()
12. {
13. return "Hello World";
14. }
15. }

We can also improve the above code by using


the @GetMapping annotation instead of @RequestMapping. Here the
method specification is not required.

1. package com.javatpoint.server.main;
2. import org.springframework.web.bind.annotation.GetMapping;
3. import org.springframework.web.bind.annotation.RestController;
4. //Controller
5. @RestController
6. public class HelloWorldController
7. {
8. //using get method and hello-world as URI
9. @GetMapping(path="/hello-world")
10. public String helloWorld()
11. {
12. return "Hello World";
13. }
14. }

Step 3: Run the RestfulWebServiceApplication. It displays the


string Hello World on the browser.

Enhancing the Hello World Service to Return a Bean


In this section, we are going to generate a bean for the method
helloWorld().

Step 1: Create a helloWorldBean() method


in HelloWordController.java file. Map the URI to "/hello-world-bean"
and return HelloWorldBean.

HelloWorldController.java

1. package com.javatpoint.server.main;
2. import org.springframework.web.bind.annotation.GetMapping;
3. import org.springframework.web.bind.annotation.RestController;
4. //Controller
5. @RestController
6. public class HelloWorldController
7. {
8. //using get method and hello-world URI
9. @GetMapping(path="/hello-world")
10. public String helloWorld()
11. {
12. return "Hello World";
13. }
14. @GetMapping(path="/hello-world-bean")
15. public HelloWorldBean helloWorldBean()
16. {
17. return new HelloWorldBean("Hello World"); //constructor of H
elloWorldBean
18. }
19. }
Step 2: Create a class HelloWorldBean.

Step 3: Generate Getters and Setters.

Right-click -> Source -> Generate Getters and Setters -> check the box ->
Ok

Step 4: Generate toString()..

Right-click -> Source -> Generate toString().. -> Ok

HelloWorldBean.java

1. package com.javatpoint.server.main;
2. public class HelloWorldBean
3. {
4. public String message;
5. //constructor of HelloWorldBean
6. public HelloWorldBean(String message)
7. {
8. this.message=message;
9. }
10. //generating getters and setters
11. public String getMessage()
12. {
13. return message;
14. }
15. public void setMessage(String message)
16. {
17. this.message = message;
18. }
19. @Override
20. //generate toString
21. public String toString()
22. {
23. return String.format ("HelloWorldBean [message=%s]", mess
age);
24. }
25. }
Step 5: Launch the HelloWorldController. The URL of the browser
changes to localhost:8080/hello-world-bean.

It returns the message "Hello World" in JSON format.

1. {
2. message: "Hello World"
3. }

You might also like