Download as pdf or txt
Download as pdf or txt
You are on page 1of 113

Advanced Java

Anytime, anywhere

-Professor Shweta Waghmare


Module 6 : Getting Started with
Spring Boot
Topics in Module 6

❏ Spring Boot and Database


❏ Spring Boot Web Application Development
❏ Spring Boot RESTful WebServices
❏ Self learning topics: Understanding Transaction Management in Spring
Ref :
https://docs.spring.io/spring-framework/docs/4.2.x/spring-framework-reference/html/transaction.html#:
~:text=The%20Spring%20Framework%20provides%20a,Java%20Data%20Objects%20(JDO).
Spring Boot
Java Spring Framework (Spring Framework) is a popular, open source, enterprise-level
framework for creating standalone, production-grade applications that run on the Java
Virtual Machine (JVM).(regular and intensive use with real users)

Java Spring Boot (Spring Boot) is a tool that makes developing web application and
microservices with Spring Framework faster and easier through three core
capabilities:

1. Autoconfiguration
2. An opinionated approach to configuration
3. The ability to create standalone applications

These features work together to provide you with a tool that allows you to set up a
Spring-based application with minimal configuration and setup.
Why is Spring Framework so popular?(Just for ref)

Spring Framework offers a dependency injection feature that lets objects define their own
dependencies that the Spring container later injects into them. This enables developers to
create modular applications consisting of loosely coupled components that are ideal for
microservices and distributed network applications.

Spring Framework also offers built-in support for typical tasks that an application needs to
perform, such as data binding, type conversion, validation, exception handling, resource
and event management, internationalization, and more

In sum, Spring Framework provides developers with all the tools and features the
need to create loosely coupled, cross-platform Java EE applications that run in any
environment.
What is micro service?
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.
Micro services offers the following advantages to its developers −
● Easy deployment
● Simple scalability
● Compatible with Containers
● Minimum configuration
● Lesser production time
What is spring boot?
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.

Advantages
Spring Boot offers the following advantages to its developers −
● Easy to understand and develop spring applications
● Increases productivity
● Reduces the development time
Spring boot goals-
Spring Boot is designed with the following goals −
● 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
Why Spring Boot?
You can choose Spring Boot because of the features and benefits it offers as given
here −
● 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
What Spring Boot adds to Spring Framework

Autoconfiguration
Autoconfiguration means that applications are initialized with pre-set dependencies that
you don't have to configure manually. As Java Spring Boot comes with built-in
autoconfiguration capabilities, it automatically configures both the underlying Spring
Framework and third-party packages based on your settings (and based on best
practices, which helps avoid errors).

Even though you can override these defaults once the initialization is complete, Java
Spring Boot's auto configuration feature enables you to start developing your
Spring-based applications fast and reduces the possibility of human errors.
What Spring Boot adds to Spring Framework
Opinionated approach

Spring Boot uses an opinionated approach to adding and configuring starter dependencies,
based on the needs of your project. Following its own judgment, Spring Boot chooses which
packages to install and which default values to use, rather than requiring you to make all those
decisions yourself and set up everything manually.

You can define the needs of your project during the initialization process, during which you
choose among multiple starter dependencies—called Spring Starters—that cover typical use
cases.
For example, the ‘Spring Web’ starter dependency allows you to build Spring-based web
applications with minimal configuration by adding all the necessary dependencies—such as
the Apache Tomcat web server—to your project.
‘Spring Security’ is another popular starter dependency that automatically adds authentication
and access-control features to your application.
Spring Boot includes over 50 Spring Starters, and many more third-party starters are available.
What Spring Boot adds to Spring Framework

Standalone applications
Spring Boot helps developers create applications that just run. Specifically, it lets you create
standalone applications that run on their own, without relying on an external web server, by
embedding a web server such as Tomcat or Netty into your app during the initialization
process.
As a result, you can launch your application on any platform by simply hitting the Run
command. (You can opt out of this feature to build applications without an embedded Web
server.)
How does it works?
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.(SpringApplication.class)
Spring Boot Starters

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.
Spring Boot Starter Actuator dependency is used to monitor and manage your application.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Spring Boot Starter Security dependency is used for Spring Security.


<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.


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Auto Configuration
Spring Boot Auto Configuration automatically configures your Spring application based on the JAR
dependencies you added in the project. For example, if MySQL database is on your class path, but you
have not configured any database connection, then Spring Boot auto configures an in-memory
database.
For this purpose, you need to add @EnableAutoConfiguration annotation or
@SpringBootApplication annotation to your main class file. Then, your Spring Boot application will be
automatically configured.
Spring Boot Application
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.
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.
Component Scan
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.
Spring boot Annotations
Spring Boot Annotations is a form of metadata that provides data about a program. In
other words, annotations are used to provide supplemental information about a
program.

It is not a part of the application that we develop.

It does not have a direct effect on the operation of the code they annotate.

It does not change the action of the compiled program.


Core spring FW annotations
@Required: It applies to the bean setter method. It indicates that the annotated bean must be
populated at configuration time with the required property, else it throws an exception
BeanInitilizationException.

@Autowired: Spring provides annotation-based auto-wiring by providing @Autowired


annotation. It is used to autowire spring bean on setter methods, instance variable, and
constructor. When we use @Autowired annotation, the spring container auto-wires the bean by
matching data-type.

@Configuration: It is a class-level annotation. The class annotated with @Configuration used by


Spring Containers as a source of bean definitions.

@ComponentScan: It is used when we want to scan a package for beans. It is used with the
annotation @Configuration. We can also specify the base packages to scan for Spring
Components.

@Bean: It is a method-level annotation. It is an alternative of XML <bean> tag. It tells the


method to produce a bean to be managed by Spring Container.
Spring fw stereotype annotation
@Component: It is a class-level annotation. It is used to mark a Java class as a bean. A Java
class annotated with @Component is found during the classpath. The Spring Framework pick
it up and configure it in the application context as a Spring Bean.

@Controller: The @Controller is a class-level annotation. It is a specialization of


@Component. It marks a class as a web request handler. It is often used to serve web pages.
By default, it returns a string that indicates which route to redirect. It is mostly used with
@RequestMapping annotation.

@Service: It is also used at class level. It tells the Spring that class contains the business logic.

@Repository: It is a class-level annotation. The repository is a DAOs (Data Access Object) that
access the database directly. The repository does all the operations related to the database.
Spring boot annotation
@EnableAutoConfiguration: It auto-configures the bean that is present in the classpath and
configures it to run the methods. The use of this annotation is reduced in Spring Boot 1.2.0
release because developers provided an alternative of the annotation, i.e.
@SpringBootApplication.

@SpringBootApplication: It is a combination of three annotations


@EnableAutoConfiguration, @ComponentScan, and @Configuration.

@RestController: The @RestController annotation from Spring Boot is basically a quick


shortcut that saves us from always having to define @ResponseBody.
Spring MVC and REST Annotation
@RequestMapping: It is used to map the web requests. It has many optional elements like
consumes, header, method, name, params, path, produces, and value. We use it with the class as
well as the method.
@GetMapping: It maps the HTTP GET requests on the specific handler method. It is used to create
a web service endpoint that fetches It is used instead of using: @RequestMapping(method =
RequestMethod.GET)
@PostMapping: It maps the HTTP POST requests on the specific handler method. It is used to
create a web service endpoint that creates It is used instead of using: @RequestMapping(method
= RequestMethod.POST)
@PutMapping: It maps the HTTP PUT requests on the specific handler method. It is used to create
a web service endpoint that creates or updates It is used instead of using:
@RequestMapping(method = RequestMethod.PUT)

Spring Boot Architecture
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:

● Presentation Layer
● Business Layer
● Persistence Layer
● 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 - SpringApplication Example

● SpringApplication#run SpringApplication.run(Classname.class, args)


bootstraps a spring application as a stand-alone application from the main
method.
● It creates an appropriate ApplicationContext instance and load beans.
● It also runs embedded Tomcat server in Spring web application
@SpringBootApplication

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

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


● @ComponentScan: It scans the package where the application is located.
● @Configuration: It allows us to register extra beans in the context or import additional
configuration classes.
Internal working of Spring Boot
package com.exampleboot.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootRestApplication {

public static void main(String[] args) {


SpringApplication.run(SpringBootExampleSts.class, args);
}
}
Spring MVC the view tier
A Spring MVC is a Java framework which is used to build web applications. It follows the
Model-View-Controller design pattern. It implements all the basic features of a core
spring framework like Inversion of Control, Dependency Injection.
Ways to Create Spring Boot Project:
1. Create Maven project and add Starter Project
2. Use Spring Initializr : https://start.spring.io/
3. Use IDE like STS : https://spring.io/tools
4. Spring boot Command Line Interface
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.

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

package com.tutorialspoint.demo;
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);
}
}
Write a Rest Endpoint
To write a simple Hello World Rest Endpoint in the Spring Boot Application main
class file itself, follow the steps shown below −

● Firstly, add the @RestController annotation at the top of the class.


● Now, write a Request URI method with @RequestMapping annotation.
● Then, the Request URI method should return the Hello World string.
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController

public class DemoApplication {


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

}
@RequestMapping(value = "/")
public String hello() {
return "Hello World";

}
}
Right Click the project -> Maven -> Update Project

Then Re-run the project.


---------------------------------------------------------------------------
Main class is configurable in pom.xml

<properties> <start-class>com.bt.collab.alu.api.webapp.Application</start-class>
</properties>
1.Installation of Spring Tools Through Eclipse MarketPlace
Write a program to create a simple Spring Boot application that prints a message.
Step 1: New spring starter project File->New->Other->Spring->Spring Start Project
Step 2: -Give Project Name->MVC_DEMO->Next button

Step 3: Add Spring starter project Dependencies


Select following dependencies:

1.Select Spring Boot Dev Tools(this tools helps in quick deployment of change
without restart of the server or container

2. Select thymleaf: This component is used for view component deployment


For view component deployment MVC Consist of model view controller. This
helps us to have view component development

3. Select Spring web: It is required dependency for web application


development which build web including restful applications using spring mvc
and it has an embedded tomcat server in it.
Step 4: Click on next ->click on finish

Step 5:Check pom.xml file In pom.xml -> Check the dependencies spring
bootstarter,web dev tools,thymleaf
Step 6: Check the main the application file which main entry point of spring
boot application is scr->package->demoApplication

1. Springboot application annotation and main method

2. SpringApplication.run(Assignment101Application.class, args);

Above line 2 is default created whenever we create the project

Step 7:Run this application->spring boot app->


Step 9: Create html file in template folder
Spring boot and database
Spring boot connect to postgresql db
Connect to posgresql:
● Spring boot with jdbc template
● Spring boot with spring data JPA & Hibernate
Software Programs:
● JDK
● Spring tool suite IDE(STS)
● PostgreSql and PgAdmin
Spring boot and database
How to configure and write code for connecting to a PostgreSQL database
In a Spring Boot application, the two common ways:
● Use Spring JDBC with JdbcTemplate to connect to a PostgreSQL database
● Use Spring Data JPA to connect to a PostgreSQL database

To connect a Spring Boot application to a PostgreSQL database, you need follow these
steps below:
● Add a dependency for PostgreSQL JDBC driver, which is required to allow Java
applications to be able to talk with a PostgreSQL database server.
● Configure data source properties for the database connection information
● Add a dependency for Spring JDBC or Spring Data JPA, depending on your need:
○ Use Spring JDBC for executing plain SQL statements
○ Use Spring Data JPA for more advanced use, e.g. mapping Java classes to
tables and Java objects to rows, and take advantages of the Spring Data JPA
API.
1. Add dependency for PostgreSQL JDBC Driver
Declare the following dependency in your project’s pom.xml file:

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
2. Configure Data Source Properties
Next, you need to specify some database connection information in the Spring Boot
application configuration file (application.properties) as
follows:(src/main/resources/application.properties)

spring.datasource.url=jdbc:postgresql://localhost:5432/shopme
spring.datasource.username=postgres
spring.datasource.password=password

Here, the JDBC URL points to a PostgreSQL database server running on localhost.
Update the JDBC URL, username and password according to your environment.
3. Connect to PostgreSQL Database with Spring JDBC
In the simplest case, you can use Spring JDBC with JdbcTemplate to work with
a relational database. So add the following dependency to your Maven project
file:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
4. Connect to PostgreSQL Database with Spring Data JPA
If you want to map Java classes to tables and Java objects to rows and take
advantages of an Object-Relational Mapping (ORM) framework like Hibernate, you
can use Spring Data JPA. So declare the following dependency to your project:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Besides the JDBC URL, username and password, you can also specify some additional properties
as follows:()

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect
And you need to code an entity class (a POJO Java class) to map with the corresponding table in the
database, as follows:
package net.codejava;
import javax.persistence.*;
@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String email;
// getters and setters…

}
Then you need to declare a repository interface as follows:

Declare repository interface for our entity. This interface will act as a bridge between the
Java class and the actual table in the database.

package net.codejava;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentRepository extends JpaRepository<Student, Integer> {
}
And then you can use this repository in a Spring MVC controller or business class as follows

@Controller
public class StudentController {//business logic
@Autowired
private StudentRepository studentRepo;

@GetMapping("/students")
public String listAll(Model model) {
List<Student> listStudents = studentRepo.findAll();
model.addAttribute("listStudents", listStudents);
return "students";
}
}
Spring Boot with spring data JPA
JPa Repository

JpaRepository is JPA 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.

Note: Command Line Runner is an interface. It is used to execute the code after the Spring
Boot application started.
Spring Boot JPA
What is JPA?
● Spring Boot JPA is a Java specification for managing relational data in Java
applications. It allows us to access and persist data between Java object/ class and
relational database.
● JPA follows Object-Relation Mapping (ORM). It is a set of interfaces.
● It also provides a runtime EntityManager API for processing queries and transactions on
the objects against the database.
● It uses a platform-independent object-oriented query language JPQL (Java Persistent Query
Language).

In the context of persistence, it covers three areas:

● The Java Persistence API


● Object-Relational metadata
● The API itself, defined in the persistence package

JPA is not a framework. It defines a concept that can be implemented by any framework.
Why should we use JPA?
JPA is simpler, cleaner, and less labor-intensive than JDBC, SQL, and handwritten mapping. JPA is
suitable for non-performance oriented complex applications. The main advantage of JPA over JDBC is
that, in JPA, data is represented by objects and classes while in JDBC data is represented by tables and
records. It uses POJO to represent persistent data that simplifies database programming.

There are some other advantages of JPA:

● JPA avoids writing DDL in a database-specific dialect of SQL. Instead of this, it allows mapping in
XML or using Java annotations.
● JPA allows us to avoid writing DML in the database-specific dialect of SQL.
● JPA allows us to save and load Java objects and graphs without any DML language at all.
● When we need to perform queries JPQL, it allows us to express the queries in terms of Java
entities rather than the (native) SQL table and columns.
JPA Features
● It is a powerful repository and custom object-mapping abstraction.
● It supports for cross-store persistence. It means an entity can be partially stored in MySQL
and Neo4j (Graph Database Management System).
● It dynamically generates queries from queries methods name.
● The domain base classes provide basic properties.
● It supports transparent auditing.
● Possibility to integrate custom repository code.
● It is easy to integrate with Spring Framework with the custom namespace.
JPA Architecture

JPA is a source to store


business entities as relational
entities. It shows how to
define a POJO as an entity
and how to manage entities
with relation.
JPA Architecture
● Persistence: It is a class that contains static methods to obtain an
EntityManagerFactory instance.
● EntityManagerFactory: It is a factory class of EntityManager. It creates and
manages multiple instances of EntityManager.
● EntityManager: It is an interface. It controls the persistence operations on objects.
It works for the Query instance.
● Entity: The entities are the persistence objects stores as a record in the database.
● Persistence Unit: It defines a set of all entity classes. In an application,
EntityManager instances manage it. The set of entity classes represents the data
contained within a single data store.
● EntityTransaction: It has a one-to-one relationship with the EntityManager class.
For each EntityManager, operations are maintained by EntityTransaction class.
● Query: It is an interface that is implemented by each JPA vendor to obtain relation
objects that meet the criteria.
JPA Class Relationships
● The relationship between EntityManager and EntiyTransaction is one-to-one. There is an
EntityTransaction instance for each EntityManager operation.
● The relationship between EntityManageFactory and EntiyManager is one-to-many. It is a
factory class to EntityManager instance.
● The relationship between EntityManager and Query is one-to-many. We can execute any
number of queries by using an instance of EntityManager class.
● The relationship between EntityManager and Entity is one-to-many. An EntityManager
instance can manage multiple Entities.
JPA Class Relationships
Spring Boot Web application development
• Spring boot 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.
• Spring Boot Starter Web
– There are two important features of spring-boot-starter-web:
• It is compatible for web development
• Auto configuration

It helps develop applications rapidly as most of the application-specific configuration is taken


care of by the framework. Spring boot also comes with an in-built servlet container, which
helps run and test the application quickly.
Spring Boot Web application development
• Starter of Spring web uses Spring MVC, REST and Tomcat as a default embedded
server.
• The single spring-boot-starter-web dependency transitively pulls in all dependencies
related to web development.
• It also reduces the build dependency count.
• The spring-boot-starter-web transitively depends on the following:
– org.springframework.boot:spring-boot-starter
– org.springframework.boot:spring-boot-starter-tomcat
– org.springframework.boot:spring-boot-starter-validation
– com.fasterxml.jackson.core:jackson-databind
– org.springframework:spring-web
– org.springframework:spring-webmvc
Spring Boot Embedded Web Server
• Each Spring Boot application includes an embedded server.
• Embedded server is embedded as a part of deployable application.
• The advantage of embedded server is, we do not require pre-installed server in the
environment.
• With Spring Boot, default embedded server is Tomcat.
• Spring Boot also supports another two embedded servers:
– Jetty Server
– Undertow Server
Need to do (practical):
Prerequisites
● Java 1.8+
● Maven

Install Spring Tool Suite


Go to Eclipse -> Help -> Market Place and search “Spring Tools” to install.

Create a Project
After the Spring Boot tool installation, let us create a spring boot starter project named
“HelloWorld”

Check Pom.xml
Let’s check the pom.xml and make sure its java version is set to 8.
Check Main Class(Web application with static page)
Spring Boot framework will create the “HelloWorldApplication.java” class in the
"com.example.hello” package. This class will be annotated with @SpringBootApplication. This
is the entry point of the spring boot application.
package com.example.hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication.class, args);
}
}
Run Project
As the "HelloWorld" project is created successfully, let's check it by running project as “Spring
Boot App.” This process will start the inbuilt servlet container and run the application. The
application can be accessed at 8080 port.
• The @SpringBootApplicationannotation does the magic work to start the embedded
Tomcat server, configure Spring Dispatcher Servlet, etc.
• Using @SpringBootApplication in your main class is equivalent to following 3
annotations
– @Configuration as a source of bean definitions
– @EnableAutoConfiguration It gives Spring Boot an idea as to how you want to
configure your application.
– @ComponentScan to automatically pick up all Spring components,
including @Configuration classes

• And there are two default directories and one properties file in
the src/main/resources folder.

– static: put your static files here, e.g. HTML files.


– templates: put your template files here, e.g. ThymeLeaf files.
– application.properties: specify additional configurations here, e.g. logging, Spring
MVC view resolver, server port number, etc.
• If you have the static welcome page (index.html) for the application, put it under
the src/main/resources/static directory.
index.html file
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>My Contacts - Spring Boot Web Application Example</title>
</head>
<body>
<h1>My Contacts</h1>
<a href="/list_contact">Click here to list all contacts</a>
</body>
</html>
Output in console
• To run the application click Run As > Java Application.

Notice the last two lines in the Console view:


1. Tomcat started on port(s): 8080 (http) with context path ''
2. Started SpringBootWebAppExampleApplication in 4.254 seconds (JVM running for
4.79)
By default, the server is listening on port number 8080 with empty context path.
Output in internal web browser(in IDE)
Output in web browser
• Type the following URL in your web browser:
– http://localhost:8080/
Web application with Model, Business and Controller Classes
SpringBootWebAppExampleApplication.java
package net.mu.SpringBootWebAppExample;

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

@SpringBootApplication
public class SpringBootWebAppExampleApplication {

public static void main(String[] args) {


SpringApplication.run(SpringBootWebAppExampleApplication.class, args);
}
}
The model class
Contact.java
package net.mu.SpringBootWebAppExample;
public class Contact {
private String name;
private String email;
private String country;
public Contact() {
super(); }

public Contact(String name, String email, String country) {


super();
this.name = name;
this.email = email;
this.country = country;
} // getters and setters }
A business class that implements a method to return a hard-coded List of Contact objects.
ContactBusiness.java //buisness logic
package net.mu.SpringBootWebAppExample;
import java.util.ArrayList;
import java.util.List;
public class ContactBusiness {
public List<Contact> getContactList() {
List<Contact> listContact = new ArrayList<>();

listContact.add(new Contact("Marry John", "marry.john@gmail.com", "USA"));


listContact.add(new Contact("Tom Smith", "tomsmith@outlook.com", "England"));
listContact.add(new Contact("John Purcell", "john123@yahoo.com", "Australia"));
listContact.add(new Contact("Siva Krishna", "sivakrishna@gmail.com", "India"));
return listContact;
}
}
A Spring controller class to handle requests .
AppController .java

package net.mu.SpringBootWebAppExample;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class AppController {
@RequestMapping("/list_contact")
public String listContact(Model model) {
ContactBusiness business = new ContactBusiness();
List<Contact> contactList = business.getContactList();
model.addAttribute("contacts", contactList);
return "contact";
} }
• Standard Spring web controller class annotated with the @Controller annotation.

• @RequestMapping annotation ensures that HTTP requests to / list_contact are mapped


to the listContact() method.

• The @RequestMapping("/list_contact") annotation specifies that the listContact() method


is responsible to handle requests coming from the /list_contact URL.

• This method uses the ContactBusinessclass to get a List of Contact objects and puts this
collection to a Model object, which will be then used by the view.

• Finally it returns the view name “contact”, which can be resolved to a JSP page or a
ThymeLeaf template, depending on our configuration.
• To use JSP with Spring Boot add the following two dependencies in the pom.xml file:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
• The dependency tomcat-embed-jasper is JSP Engine for Tomcat. It is required to enable
JSP with Spring Boot.
• To configure Spring MVC view resolver, open the application.properties file and put the
following properties
1. spring.mvc.view.prefix=/WEB-INF/jsp/
2. spring.mvc.view.suffix=.jsp
contact.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<body>
<h1 align="center">My Contact List</h1>
<br/> <table border="1" cellpadding="10">
<tr> <th>Name</th><th>Email</th><th>Country</th>
</tr>
<c:forEach var="con" items="${contacts}">
<tr>
<td>${con.name}</td>
<td>${con.email}</td>
<td>${cont.country}</td>
</tr>
</c:forEach>
</table></body></html>
What is web service?
• 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.
• Any software, application, or cloud technology that uses standardized web protocols
(HTTP or HTTPS) to connect, interoperate, and exchange data messages –
commonly XML (Extensible Markup Language) – across the internet is considered a
web service.
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. For this reason, REST APIs are
sometimes referred to RESTful APIs.
● A REST API is designed to provide a lightweight form of communication (less
bandwidth) between producer (ex: Twitter) and consumer (ex: Twitter client)
● REST APIs provide a flexible, lightweight way to integrate applications, and have
emerged as the most common method for connecting components in
microservices architectures.
How REST APIs work
REST APIs communicate via HTTP requests to perform standard database functions like creating,
reading, updating, and deleting records (also known as CRUD) within a resource.
For example, a REST API would use a GET request to retrieve a record, a POST request to create
one, a PUT request to update a record, and a DELETE request to delete one.
All HTTP methods can be used in API calls.
A well-designed REST API is similar to a website running in a web browser with built-in HTTP
functionality.

The state of a resource at any particular instant, or timestamp, is known as the resource
representation. This information can be delivered to a client in virtually any format including
JavaScript Object Notation (JSON), HTML, XLT, Python, PHP, or plain text.

Request headers and parameters are also important in REST API calls because they include
important identifier information such as metadata, authorizations, uniform resource identifiers
(URIs), caching,cookies and more. Along with conventional HTTP status codes, are used within
well-designed REST APIs.
RESTful API is an application program
interface (API) that uses HTTP requests to
GET, PUT, POST and DELETE data
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).
Introduction to RESTful Web Services
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:

● GET: It reads a resource.


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

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


POST /users: It creates a user. GET /users/{id}/posts/post_id: It retrieve the detail
GET /users/{id}: It retrieves the detail of a user. of a specific post.
GET /users: It retrieves the detail of all users. POST / users/{id}/ posts: It creates a post of the
DELETE /users: It deletes all users. user.
Spring Boot - Building RESTful Web Services
Spring Boot provides a very good support to building RESTful Web Services for enterprise
applications. This chapter will explain in detail about building RESTful web services using Spring
Boot.
Note − For building a RESTful Web Services, we need to add the Spring Boot Starter Web
dependency into the build configuration file.
If you are a Maven user, use the following code to add the below dependency in your pom.xml file

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

If you are a Gradle user, use the following code to add the below dependency in your build.gradle
file. compile('org.springframework.boot:spring-boot-starter-web')
Spring Boot - Building RESTful Web Services

Rest Controller
The @RestController annotation is used to define the RESTful web services.
It serves JSON, XML and custom response.
Its syntax is shown below −

@RestController
public class ProductServiceController {
}
Spring Boot - Building RESTful Web Services

Request Mapping
The @RequestMapping annotation is used to define the Request URI to access the REST
Endpoints. We can define Request method to consume and produce object. The default request
method is GET.
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProducts() { }

@GetMapping is a composed annotation that acts as a shortcut for


@RequestMapping(method = RequestMethod.GET).
We can apply @GetMapping only on method level and @RequestMapping annotation can be
applied on class level and as well as on method level.
@GetMapping is the newer annotaion.
Spring Boot restful Web services
Request Body
The @RequestBody annotation is used to define the request body content type.
//create new service=@RequestBody
public ResponseEntity<Object> createProduct(@RequestBody Product product) {
}
Spring Boot restful Web services
Path Variable
The @PathVariable annotation is used to define the custom or dynamic request URI.
The Path variable in request URI is defined as curly braces {} as shown below −

public ResponseEntity<Object> updateProduct(@PathVariable("id") String id) {


//update
//delete
}
Spring Boot restful Web services
Request Parameter
The @RequestParam annotation is used to read the request parameters from the Request
URL. By default, it is a required parameter. We can also set default value for request
parameters as shown here −
public ResponseEntity<Object> getProduct(

@RequestParam(value = "name", required = false, defaultValue = "honey") String name) {

}
Get API(Read operation)
The default HTTP request method is GET.

This method does not require any Request Body.

You can send request parameters and path variables to define the custom or dynamic URL.
Post API(Create Operation)
The HTTP POST request is used to create a resource.

This method contains the Request Body.

We can send request parameters and path variables to define the custom or dynamic URL.
Put API
The HTTP PUT request is used to update the existing resource

This method contains a Request Body.

We can send request parameters and path variables to define the custom or dynamic URL.
Delete API
The HTTP Delete request is used to delete the existing resource.

This method does not contain any Request Body.

We can send request parameters and path variables to define the custom or dynamic URL.
Spring Boot - Building RESTful Web Services
The Spring Boot main application class – DemoApplication.java

package com.tutorialspoint.demo;
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);
}
The POJO class – Product.java
package com.tutorialspoint.demo.model;
public class Product {
private String id;
private String name;

public String getId() {


return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}
The Rest Controller class – ProductServiceController.java
package com.tutorialspoint.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.tutorialspoint.demo.model.Product;

@RestController

public class ProductServiceController {

private static Map<String, Product> productRepo = new HashMap<>();


static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);

Product almond = new Product();


almond.setId("2");
almond.setName("Almond");
productRepo.put(almond.getId(), almond);
}
@RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Object> delete(@PathVariable("id") String id) {
productRepo.remove(id);
return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
}
@RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
//update or create
public ResponseEntity<Object> updateProduct(@PathVariable("id") String id,
@RequestBody Product product)
{
product.setId(id);
productRepo.put(id, product);
return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
}

@RequestMapping(value = "/products", method = RequestMethod.POST)


public ResponseEntity<Object> createProduct(@RequestBody Product product) {
productRepo.put(product.getId(), product);
return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
}

@RequestMapping(value = "/products")
public ResponseEntity<Object> getProduct() {
return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
}
GET API URL is: http://localhost:8080/products
POST API URL is: http://localhost:8080/products
PUT API URL is: http://localhost:8080/products/3
DELETE API URL is: http://localhost:8080/products/3

You might also like