0% found this document useful (0 votes)
3 views

SpringBoot

The document provides an overview of the Spring and Spring Boot frameworks, detailing their functionalities, prerequisites, and components such as WAR and JAR files, application context, dependency injection, and configuration files. It also includes examples of a Book API project, explaining the roles of entity classes, repositories, and controllers, as well as the MVC architecture in Spring Boot. Additionally, it discusses the use of JPA for database interactions and the benefits of using Spring Boot for streamlined application development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

SpringBoot

The document provides an overview of the Spring and Spring Boot frameworks, detailing their functionalities, prerequisites, and components such as WAR and JAR files, application context, dependency injection, and configuration files. It also includes examples of a Book API project, explaining the roles of entity classes, repositories, and controllers, as well as the MVC architecture in Spring Boot. Additionally, it discusses the use of JPA for database interactions and the benefits of using Spring Boot for streamlined application development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

SPRING/SPRINGBOOT

Q) What is Spring?
We can make enterprise level application and
web application using Spring framework.

Pre Requisites for Spring Framework

 Java (at least until Threads, exception


handling and collection)
 If you’re using any framework you need
to use some build tools, we’re going to be
using Maven.
 JDBC.
 Hibernate.
Both WAR and JAR files are archive formats
used in Java to bundle files together for
easier distribution and deployment. They
serve different purposes though.

Q) What are WAR files?

A) Web Application Archive (WAR) files are


used to package web applications including
their components (Servlets, JSP files, static
resources) for deployment on a java web
server or application server like Tomcat.

.war

Q) What are JAR files?

A) Java Archive (JAR) files are used to


package Java classes, metadata and
resources (images, configuration fils) into a
single archive for Java applications or
libraries.

.jar

Use Cases:
 Libraries or frameworks (e.g., Apache
Commons, Hibernate).
 Standalone Java applications.
 Reusable components for other Java projects.

 APPLICATION CONTEXT

Application context is like a container or manager


for all the beans in your application. It knows which
objects are created, creates them and wires them
together so the application runs smoothly.

It is a type/subcategory of Spring container and is


more powerfl than BeanFactory.

 Spring.xml
In Spring Framework, you traditionally create an
XML file (like Spring.xml) to configure beans and
define dependencies. However, in Spring Boot,
this is not required in most cases. Spring Boot
was designed to simplify and modernize Spring
applications by eliminating the need for
explicit XML configuration. Instead, it uses
Java-based configuration and convention-
over-configuration principles.

 Annotation based configuration

SPRINGBOOT
Springboot isn’t a replacement for Spring
framework, Springboot gives you dependences and
helps you configure JAR files. Springboot helps us
get a production ready project, all the basic
configurations will be done by Springboot.

Springboot provides us with an embedded server. We’ll


be making JAR files now and inside the JAR file will be
TOMCAT embedded in it. You can run your project on
any JVM.

Springboot will not generate any XML files for you.


 DEPENDENCY INJECTION

Dependency Injection (DI) is a way of making


your code more flexible, reusable, and easier to
test by letting the framework (like Spring Boot)
handle the creation and management of objects
(dependencies) that your classes need.

Spring Boot automatically manages your


dependencies for you using DI. You just need to:
1. Mark your dependencies as @Component,
@Service, or @Repository (to tell Spring they
should be managed).
2. Use @Autowired to inject those dependencies
where needed.

Lets say you want to build a laptop. Laptop has


some parts like RAM, springs etc. Apple don’t build
all the parts by themselves, the components are
built by some other companies.
The same way if you wanna build a project, if you
have an object and that object is dependent on
other object. In Java we first create class and then
we create the objects.

We want to do loose coupling in which one object is


not dependent on another. Example lets say our
laptop has a Hitachi Harddrive and in the future we
want to replace it with a Samsung harddrive.
That’s why we have abstract classes so in the
future we can change.

We want to inject this harddrive object into this


Laptop class and the way you can do that is by
using some external service that will inject the
dependency. We have a concept known as
dependency injection containers, they are
responsible for creating an object for you and then
they’ll inject in your class.

class Laptop
{
@Autowired
Harddrive obj1;
}

Another reason for loose coupling is TESTING, we


usually always wanna test our software as a whole but
we should always also do unit testing.
 application.properties

application.properties is a file in a Spring Boot


application is a configuration file where you can
define various settings for your application. It is
located in the src/main/resources directory by
default.

It is used to:

i) Set application level properties

Configure aspects of our application such as


server ports, database credentials, logging
levels etc.

ii) Customize default settings

Override Spring Boot’s default configuration


with your own.

iii) Externalize configuration

Keep configuration separate from the code,


making it easy to modify without changing the
application.
 BOOK API PROJECT

1) Book.java

This is your entity class which defines the


structure of a “Book” in your system.

Code:

package com.example.demo.model;

// Represents a database entity


import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity // Marks this class as a database table


public class Book {

@Id // Marks 'id' as the primary key


@GeneratedValue(strategy =
GenerationType.IDENTITY)
private Long id; // Unique identifier for each
book

private String title; // Title of the book


private String author; // Author of the book

// Default constructor (required by JPA)


public Book() {
}
// Getters and Setters (used to access and
modify fields)
public Long getId() {
return id;
}

public void setId(Long id) {


this.id = id;
}

public String getTitle() {


return title;
}

public void setTitle(String title) {


this.title = title;
}

public String getAuthor() {


return author;
}

public void setAuthor(String author) {


this.author = author;
}
}

--- @Entity tells Springboot that this class is tied


to a database table

---@Id indicates the primary key field


---@GeneratedValue auto generates unique IDs
for books in the Database
2) BookRepository.java

This interface acts as the link between your app


and the database.

CODE:

package com.example.demo.repository;

import com.example.demo.model.Book;
import
org.springframework.data.jpa.repository.JpaRepo
sitory;
import
org.springframework.stereotype.Repository;

import java.util.List;

@Repository // Marks this interface as a Spring


repository
public interface BookRepository extends
JpaRepository<Book, Long> {

// Custom method to find books by title


List<Book> findByTitle(String title);
}

---@Repository marks this as a Spring managed


component.
---JpaRepository<Book, Long>: Provides
default methods to interact with the database,
like save(), findById(), and deleteById().

--- findByTitle(): A custom method for searching


books by their title.

3) BookController.java

This is the controller layer, responsible for


handling HTTP requests and sending responses.

CODE:

package com.example.demo.controller;

import
com.example.demo.exception.BookIdMismatchE
xception;
import
com.example.demo.exception.BookNotFoundExc
eption;
import com.example.demo.model.Book;
import
com.example.demo.repository.BookRepository;
import
org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController // Marks this as a REST API


controller
@RequestMapping("/api/books") // Maps
requests starting with '/api/books'
public class BookController {

private final BookRepository bookRepository;

// Constructor-based dependency injection


public BookController(BookRepository
bookRepository) {
this.bookRepository = bookRepository;
}

// Fetch all books


@GetMapping
public List<Book> findAll() {
return bookRepository.findAll(); // Fetches
all books from the database
}

// Fetch a single book by ID


@GetMapping("/{id}")
public Book findOne(@PathVariable Long id) {
return bookRepository.findById(id)
.orElseThrow(BookNotFoundException::
new); // Throws exception if not found
}

// Fetch books by title


@GetMapping("/title/{bookTitle}")
public List<Book> findByTitle(@PathVariable
String bookTitle) {
return
bookRepository.findByTitle(bookTitle); // Calls the
custom method in the repository
}

// Add a new book


@PostMapping
public Book create(@RequestBody Book book)
{
return bookRepository.save(book); // Saves
the book to the database
}

// Update an existing book


@PutMapping("/{id}")
public Book update(@RequestBody Book book,
@PathVariable Long id) {
if (!book.getId().equals(id)) {
throw new BookIdMismatchException(); //
Throws exception if IDs don't match
}
bookRepository.findById(id)
.orElseThrow(BookNotFoundException::
new); // Ensures the book exists
return bookRepository.save(book); //
Updates the book
}

// Delete a book by ID
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
bookRepository.findById(id)
.orElseThrow(BookNotFoundException::
new); // Ensures the book exists
bookRepository.deleteById(id); // Deletes
the book
}
}

 @RestController: Marks this as a REST API


controller.

 Endpoints:

 GET /api/books: Fetch all books.


 GET /api/books/{id}: Fetch a book by ID.
 GET /api/books/title/{bookTitle}: Fetch books by
title.
 POST /api/books: Add a new book.
 PUT /api/books/{id}: Update an existing book.
 DELETE /api/books/{id}: Delete a book by ID.
The moment you say getBean the framework will
say that the developer wants a bean here of type
Alien.

When you use @Component, it marks a class as


a Spring managed bean. It tells Spring to
automatically detect it and register it as a bean
in the Spring Container.
Spring framework is injecting this object into
your application (Dependency injection).
Spring framework uses singleton design pattern
where it creates only one instance.
 SPRING BOOT MVC

Client sends request to server, it it server’s


responsibility to process the request and send it
back.
Client needs data. But you want that data in a well
formatted way. Servlet will create the layout and
data.

A Servlet is a Java program running on the server


that processes client requests and generates
responses. It acts as a middleman between the
client and the server's business logic.
We want something that will:

i) Accept the request (Controller)


ii) That will display to the client ( View)
iii) Holds the data (Model)
This is where we get Model View Controller (MVC).

Spring uses a special servlet called Dispatch servlet.


This is the single servlet that handles all incoming
requests. Acts as a traffic controller for your entire
application. It decides which controller method (like
your @GetMapping or @PostMapping) should process a
particular request.

The workflow looks like this:


1. Client Request: A client sends a request (e.g.,
/api/books).
2. DispatcherServlet:
o Receives the request.
o Maps it to the appropriate controller method
(e.g., your BookController.findAll()).
3. Controller:
o Executes the business logic.
o Interacts with the model (e.g.,
BookRepository).
4. View (optional):
o If needed, the controller prepares data for the
view.
o For APIs (like your Book API), this might be
JSON data instead of a traditional "view."
5. DispatcherServlet: Sends the final response back
to the client.

It will be automatically given by Spring framework.


 SAMPLE WEB APP

i) Create a JSP file under src

src/WebApp/index.jsp
ii) Create a controller

To run this we have to create a controller


first.

src/main/java/com.example.demo/
HomeController.java

iii) Tomcat Jasper


If we want to run JSP we need a Tomcat Jasper
library to convert JSP to servlet and run that servlet
on Tomcat.

If you want to convert JSP to servlet you need a


special library called Tomcat Jasper.

First add the Tomcat Jasper dependency to


pom.xml
 WEB APP USING SPRING BOOT APPLICATION
PROPERTIES FILE

Web app is a folder that is public, what if you


wanna make it private?

If you wanna do any configurations on your own,


we have this special file called
application.properties where we do our manual
configurations.

Prefix suggests that the folder we need to view is


inside the pages folder under “Web App”

Suffix suggests that it is a JSP file.


 WEB APP USING SPRING BOOT (ACCEPTING CLIENT
DATA)

home() method is a handler method that processes


the request when the /Home endpoint is accessed.

return “Home” tells Spring to return the view


named Home, Spring will resolve this to the
corresponding JSP file.

What Does This Code Do?


1. When a user accesses the
http://localhost:8080/Home endpoint with a query
parameter like ?name=Justin:
o The server extracts the name parameter (in

this case, "Justin") using


req.getParameter("name").
o It prints "HiJustin" to the console.
2. After processing the request, the method returns
"Home".
o Spring will look for a JSP file named Home.jsp

in the configured location (e.g.,


/WEB-INF/Home.jsp) and display it to the user.
Why Use HttpServletRequest?

HttpServletRequest allows you to:


 Retrieve data sent by the client (e.g., form data,
query parameters).
 Inspect headers or cookies from the request.
 Perform advanced request handling if needed.
In this example, it's used to fetch the name query
parameter from the URL.

HttpSession is used to manage data between


requests in the same user session:

HttpSession session=req.getSession()
- Retrieves or creates an HttpSession object for
the current user
- If a session already exists for the user it
retrieves it.
- If no session exists it creates a new one.

What is a session?

 A session is a way to store data on the server that


can be accessed across multiple HTTP requests
made by the same user.
 It is like a temporary storage area that exists for
the duration of a user's interaction with the server
(until the session times out or is invalidated).
 WEB APP USING SPRING BOOT ( MODEL AND VIEW)

Q) Can we accept requests without using


HttpServletRequest?

YES

@RequestParam("name"):
 Extracts a query parameter name from the URL.
For example, if the user visits:
http://localhost:8080/Home?name=justin, the
value of name will be "justin".
ModelAndView is a Spring MVC object used to
send both data and a view name to the frontend.

Q) What is JPA? (Java Persistence API)

JPA (Java Persistence API) is a Java standard for


storing, retrieving, and managing data in a
relational database using Java objects. It
removes the need for writing SQL queries by
allowing developers to interact with databases
using simple Java code.
JPA is just a specification, meaning it doesn't
provide an actual implementation. Instead,
frameworks like Hibernate, EclipseLink, and
OpenJPA implement JPA.

Why Use JPA?


 ✅ No SQL Needed → Work with Java objects
instead of writing SQL.
 ✅ Easier Database Management → Uses
annotations like @Entity, @Table, and @Id.
 ✅ Supports Multiple Databases → Works with
MySQL, PostgreSQL, H2, etc.
 ✅ Reduces Boilerplate Code → No need to
manually write INSERT, UPDATE, SELECT, etc.
 WEB APP USING SPRINGBOOT (MODEL
OBJECT)

Q) What if we want to send some more data?


It may have more parameters.

You can send the values and it can be accepted in


one object.
 SPRINGBOOT DATA JPA/MVC/H2
QUERY METHODS (PART 3)

In the AlienRepo you can make your own


methods.

The names need to make sense


otherwise wont work, example being
“findByTech” etc.
Relaunch and refresh localhost then
check console to see if the output works
out.
 SPRINGBOOT DATA JPA/MVC/H2 REST
PART 4

Till this point what we’ve done is that


we’ve created a simple application
where user fetch Aliens and adds Aliens.

We can remove the /getAlien request


mapping and the ModelViewController
and change it like this:
 SPRINGBOOT DATA JPA/MVC/H2 REST
PART 5

First change we made is that we change


the CrudRepository to JpaRepository.
JpaRepository has some extra features,
it’s an interface which extends paging
and sorting Repository which indirectly
extends CrudRepository.

Therefore we have all the features of


CrudRepository + extra features.

For example. findAll() now returns a List


instead of an iterable so we no longer
need to use the toString() method. When
you get the List, Jackson core in your
maven repository is responsible for
converting Java objects into JSON.

In REST API we have some other


methods as well like delete and update,
how will you perform these? And that’s
why we have a client to perform this, we
are gonna use POSTMAN to submit data,
post data etc.
 SPRINGBOOT DATA JPA/MVC/H2 REST
PART 6

Normally we were fetching values like


localhost:8080/alien/103.
What if we wanna send and update resources?
POSTMAN.

Using POSTMAN you can send API request, fetch


data and a lot more.

Click on the + button and now you can send


requests.
Notice how localhost:8080/aliens gave the
response to you in JSON format.
 CONTENT NEGOTIATION/ SPRINGBOOT
DATA JPA/MVC/H2 REST PART 7

The different formats in web services are


JSON, XML etc. People still use XML and what
if you want to use XML?
There is a concept called content negotiation:
As a server you have options of providing
data in different formats. As a client, they can
request data in different formats. The data
will remain the same but the formats may
vary. This is basically your concept of content
negotiation, a client can specify what they
want and a server can say this isn’t available.

If you want the data in XML then:


Key: Accept
Value: application/xml, then click on send
Unfortunately it shows empty, as springboot
shows that it doesn’t support XML.

Springboot by default supports JSON.

What if you wanna add a support for XML?


You have to go to pom.xml and add a
dependency.
Add the path and produces in the
RequestMapping too and then send the
request and you’ll get it in XML format.
And now JSON stops working. It will only
supports XML now.
 SPRINGBOOT DATA JPA/MVC/H2 REST
PART 8

In this we will be seeing how to send data to


server and how it will accepting and saving
data from the server side.

We will be posting data on the server using


POST.

We have to change the @Controller


annotation to @RestController, this tells
Springboot that this class handles RESTful API
requests and returns data like JSON/XML
instead of regular web pages.

When you want to send a POST request you


need to add @PostMapping annotation to
your server:

@PostMapping("/alien")
public Alien addAlien(@RequestBody Alien
alien)
{
repo.save(alien);
return alien;
}

This method runs when a POST request is


sent to /alien.
@RequestBody Alien alien
 This means Spring Boot takes the JSON
data from the request and converts it
into an Alien object automatically.
 SPRINGBOOT DATA JPA/MVC/H2 REST PUT
DELETE PART 9

DELETE:

In order to delete data on the server side you


need a mapping and currently we don’t have
any mapping.

This code doesn’t work because the moment


you delete a you can no longer access it:

Therefore we correct it like this:


UPDATE:
 SPRING BOOT DATA REST

Normally when we work with SPRING


MVC REST we need to create a controller.
The alienController we were using was
simply accepting the request and
performing operations.
Can we do the same thing without using
Controllers? Yes, that’s where Spring
Boot Data REST comes into play.

Create a new file:

1) Add ‘data.sql’ file in the src/resources


2) Create Alien class with getters, setters
and toString in com.justin.demo.model
3) Add AlienRepo to com.justin.demo
AlienRepo is an interface, not a class.
It extends JpaRepository<Alien, Integer>,
which means:
 This repository is for managing Alien
objects.
 The primary key (ID) of Alien is of type
Integer.
 Since it extends JpaRepository, it
automatically provides CRUD
operations (Create, Read, Update,
Delete) for Alien, so you don’t need to
write them manually.

@RepositoryRestResource(collectionReso
urceRel="aliens", path="aliens"):
1. This tells Spring Boot to
automatically create REST APIs for
AlienRepo.
2. Without writing a controller, Spring
Boot will:
3. Expose a REST API at
http://localhost:8080/aliens
4. Return JSON data for Alien objects.
5. The parameters:
6. collectionResourceRel="aliens" →
Sets the JSON key name for a
collection of aliens.
7. path="aliens" → Defines the REST
endpoint (/aliens).
What This Code Does Overall

 It creates a Spring Data JPA


repository for the Alien entity.
 It automatically provides RESTful API
endpoints for database operations.
 You can make requests like:
o GET /aliens → Get all aliens.

o POST /aliens → Add a new alien.

o PUT /aliens/{id} → Update an alien.

o DELETE /aliens/{id} → Delete an

alien.

You might also like