0% found this document useful (0 votes)
7 views43 pages

Unit 5 Spring Boot WT

Spring Boot is an open-source Java framework designed for rapid application development with minimal configuration, allowing developers to create standalone, production-ready applications quickly. It features auto-configuration, standalone application capabilities, and built-in tools for monitoring and debugging, making it ideal for modern development practices like microservices. Additionally, Spring Boot Actuator provides endpoints for monitoring application health and performance, enhancing management capabilities in production environments.

Uploaded by

Neha Khatoon
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)
7 views43 pages

Unit 5 Spring Boot WT

Spring Boot is an open-source Java framework designed for rapid application development with minimal configuration, allowing developers to create standalone, production-ready applications quickly. It features auto-configuration, standalone application capabilities, and built-in tools for monitoring and debugging, making it ideal for modern development practices like microservices. Additionally, Spring Boot Actuator provides endpoints for monitoring application health and performance, enhancing management capabilities in production environments.

Uploaded by

Neha Khatoon
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

SPRING BOOT

Spring Boot is an open-source Java-based framework used to create standalone, production-


grade Spring applications quickly and with minimal configuration.

(“Imagine you want to build a small house (a computer program). Normally, you’d have to
figure out where to get bricks, wood, nails, tools, and spend a lot of time putting everything
together from scratch.

Spring Boot is like a house kit that gives you almost everything ready — the walls, roof, and
tools — so you can quickly build your house without worrying about the tiny details.

In computer terms:

 It helps programmers build Java applications fast.


 It sets up most of the complicated stuff automatically.
 You can run your app easily without extra setup.
 It comes with helpful tools to keep your app running smoothly.

So, Spring Boot saves time and makes building apps easier, especially if you want to get things
working quickly”)

It is built on top of the Spring Framework and simplifies the process of developing Java web
applications by:

Key Features of Spring Boot:

1. Auto-Configuration: Automatically configures your application based on the libraries


present in the classpath.
2. Standalone Applications: You can run applications with a simple main() method using
an embedded server (like Tomcat, Jetty).
3. Opinionated Defaults: Offers default configurations to reduce boilerplate setup.
4. Production-Ready: Includes built-in features like health checks, metrics, and monitoring
via Spring Boot Actuator.
5. Spring Boot Starter Dependencies: Bundles common dependencies for various use
cases (like web, JPA, security) to simplify dependency management.

Example: A Basic Spring Boot Application


@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
[Link]([Link], args);
}
}
EXPLANATION:

1. @SpringBootApplication

 This is called an annotation — it’s like a special label or tag you put on your code.
 It tells Spring Boot: “Hey, this is the main class for the application. Please set up
everything automatically for me!”
 It combines three important annotations:
o @Configuration (marks the class as a source of bean definitions)
o @EnableAutoConfiguration (tells Spring Boot to guess and configure things
automatically)
o @ComponentScan (tells Spring where to look for other parts of your app)

2. public class MyApplication {

 This defines a class named MyApplication.


 Think of a class like a blueprint or a container that holds your program’s code.
 This is the main class where your app starts.

3. public static void main(String[] args) {

 This is the main method — the entry point of any Java program.
 When you run your app, the computer starts executing code from here.
 String[] args means it can accept some extra information if you want to pass any
when starting.

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

 This line tells Spring Boot to start running the application.


 [Link]() boots up Spring, creates the app context (all the necessary
parts), and launches the embedded server (like Tomcat) if it’s a web app.
 [Link] tells it which class is the main one to start from.
 args passes along any extra parameters given when the program starts.

This one file sets up a full Spring Boot application.

Why Use Spring Boot?

 Faster development and deployment


 Simplified configuration and setup
 Built-in tools for monitoring and debugging
 Good integration with modern dev practices like microservices and containerization
SPRING BOOT CONFIGURATION — what is it?

Configuration means setting up your app so it knows things like:

 Which port to run on


 Database details (username, password, URL)
 Other settings like logging, file paths, etc.

How to configure in Spring Boot?

1. Using [Link] file

This is the most common way. It’s a simple text file where you write key-value pairs.

Example:

[Link]=8081
[Link]=jdbc:mysql://localhost:3306/mydb
[Link]=root
[Link]=secret
[Link]=DEBUG

 [Link]=8081 means your app will run on port 8081 instead of the default 8080.
 [Link].* are for connecting to a database.
 [Link] controls the amount of log info you get.

2. Using [Link] file (alternative)

You can also use YAML format, which looks cleaner for big configs.

server:
port: 8081

spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: secret

3. Injecting config values into your Java code

You can use @Value annotation to get config values directly in your code.
@Value("${[Link]}")
private int port;

Or use @ConfigurationProperties to bind many properties to a class.

@Component
@ConfigurationProperties(prefix = "[Link]")
public class DataSourceConfig {
private String url;
private String username;
private String password;

// getters and setters


}

Where to put configuration files?

Put [Link] or [Link] inside:

src/main/resources/

Spring Boot will automatically load them.

Why is configuration important?

It lets you change how your app behaves without changing your code. For example, you can:

 Run your app on different ports


 Connect to different databases in development vs production
 Change log levels to see more or less info

SPRING BOOT ANNOTATIONS:


Annotations are like instructions or labels you add to your Java code so Spring Boot knows how to
handle classes and methods automatically.

Common Spring Boot Annotations and What They Do:


Annotation What It Does Example Use

Marks the main class to start the


Put on your main app class to
@SpringBootApplication app. Combines 3 other annotations
start Spring Boot.
inside it.
Annotation What It Does Example Use

Marks a class as a web controller


@RestController that sends responses as JSON or Create APIs that return data.
text.

Handles HTTP GET requests for a Maps a method to a GET


@GetMapping("/path")
URL path. request URL.

Handles HTTP POST requests for a Maps a method to a POST


@PostMapping("/path")
URL path. request URL.

Automatically “injects” a needed Inject a service or repository


@Autowired
object (dependency). automatically.

Marks a class as a Spring-managed Make your class known to


@Component
component (bean). Spring so it manages it.

Special @Component for service-


@Service Mark business logic classes.
layer classes.

Special @Component for data Mark database interaction


@Repository
access. classes.

Injects a value from config files into Get a value from


@Value("${[Link]}")
a variable. [Link].

Marks a class that provides bean Define beans in Java instead of


@Configuration
definitions (setup). XML.

Quick Example Using Annotations:

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

@RestController
public class HelloController {

@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
EXPLANATION:

1. @SpringBootApplication :

 This tells Spring Boot: "This is the main class for the app."
 It combines three things:
o @Configuration: This class can have setup/configuration.
o @EnableAutoConfiguration: Spring Boot will automatically set up things for
you based on what’s in your project.
o @ComponentScan: Spring will look for other classes to use (like controllers or
services) in this package.

2. public class MyApp {

Defines a class named MyApp. This is your main application class.

3. public static void main(String[] args) {

This is the main method, the starting point when you run your Java
program.
4. [Link]([Link], args);

 This starts the Spring Boot application.

 It creates the application context, sets up everything, and runs your app.

 [Link] tells Spring Boot which class is the main app.

5. @RestController

 Marks the class below as a controller that handles web requests.

 It means all methods inside this class will send data (like JSON or text) back in the
HTTP response.

6. public class HelloController {

Defines a class named HelloController that will handle web requests.

7. @GetMapping("/hello")
This means: When someone visits the URL /hello using an HTTP GET request,
run the method right below this annotation.

8. public String hello() {

Defines a method named hello that will be called when /hello is visited.

9. return "Hello, World!";

 This method returns the string "Hello, World!".

 Because of @RestController, this text will be sent directly to the browser or client as
the response.

In summary:

 MyApp class starts the app.


 HelloController listens for requests at /hello.
 When /hello is visited, the app sends back "Hello, World!

 @SpringBootApplication marks the main app class.


 @RestController makes HelloController handle web requests.
 @GetMapping("/hello") means when you visit /hello, you get "Hello, World!".

Why use annotations?

They reduce a lot of manual setup. Spring Boot figures out what to do based on these labels, so
you write less code and get things done faster!

What is SPRING BOOT ACTUATOR?

Spring Boot Actuator is a tool that helps you monitor and manage your Spring Boot
application while it is running.

It gives you ready-made endpoints (special URLs) to see information about your app's health,
metrics, configuration, and more — without you having to write all that monitoring code
yourself.
Why use Spring Boot Actuator?

 To check if your app is healthy (for example, is it connected to the database? Is it


running okay?)
 To see metrics like memory usage, CPU, HTTP requests, and other stats
 To view environment properties (all the config values currently in use)
 To trace logs and debug problems
 To manage the app (shut down, restart, etc.) in a controlled way (if enabled)

How to use Spring Boot Actuator?

1. Add the Actuator dependency

If you use Maven, add this to your [Link]:

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

If you use Gradle, add this to [Link]:

implementation '[Link]:spring-boot-starter-actuator'

2. Configure Actuator endpoints exposure

By default, only a few endpoints are enabled and accessible.

To expose all actuator endpoints over HTTP, add this to your [Link]:

[Link]=*

Or expose only specific endpoints:

[Link]=health,info,metrics

3. Common useful Actuator endpoints

Endpoint URL What it shows

/actuator/health App health status (UP, DOWN, etc.)


Endpoint URL What it shows

/actuator/info Info about your app (version, description)

/actuator/metrics Metrics about CPU, memory, HTTP requests

/actuator/env Current environment variables and config

/actuator/beans List of all Spring beans in the app

/actuator/loggers Change log levels at runtime

/actuator/threaddump Thread dump (useful for debugging)

/actuator/httptrace Recent HTTP requests trace

4. Example: Check app health

If you visit [Link] in your browser, you might see:

{
"status": "UP"
}

This means your app is running fine.

If something is wrong (like database is down), it might show:

{
"status": "DOWN",
"details": {
"db": {
"status": "DOWN",
"error": "Cannot connect to database"
}
}
}

5. Customize Health Checks

You can add your own health checks by implementing the HealthIndicator interface.

@Component
public class MyHealthCheck implements HealthIndicator {
@Override
public Health health() {
// Check your app's custom status
boolean everythingIsOk = checkSomething();
if (everythingIsOk) {
return [Link]().withDetail("CustomCheck", "All
good!").build();
} else {
return [Link]().withDetail("CustomCheck", "Problem
found!").build();
}
}

private boolean checkSomething() {


// Your logic here
return true;
}
}

6. Securing Actuator Endpoints

Since Actuator endpoints can expose sensitive info, it’s a good idea to protect them.

You can add Spring Security and restrict access only to authorized users.

Summary
What Actuator Does Why It’s Useful

Shows app health Know if your app and its parts are OK

Displays metrics (CPU, memory) Monitor app performance in real time

Shows configuration info Debug environment and config problems

Lets you change logging levels Adjust logging without restarting app

Provides debugging info (threads, HTTP requests) Helps troubleshoot issues faster

SPRING BOOT ACTUATOR:

Spring Boot Actuator is a powerful submodule of Spring Boot that helps you monitor and
manage your Spring Boot application in production. It provides a set of built-in endpoints that
expose operational information about the application—such as health, metrics, environment
properties, and more—through HTTP or JMX.
(Think of your Spring Boot application like a car. It runs, does its job, and takes you places
(like processing data or serving a website).

But how do you know:

 Is the engine running okay?


 How fast is it going?
 Is there enough fuel?
 Is anything broken?

👉 You need a dashboard or indicator lights — that’s exactly what Spring Boot Actuator
gives you.)

What Does It Actually Do?

Spring Boot Actuator adds special URLs (called endpoints) to your app.

You can open these in a browser or tool like Postman and see helpful info.

Endpoint Description
/actuator/health Health info (DB, disk space, services)
/actuator/info Static application info (from [Link])
/actuator/metrics Application metrics (memory, GC, request count)
/actuator/env Environment properties (props, env vars, etc.)
/actuator/beans Lists all Spring beans with dependencies
/actuator/configprops Shows configuration properties and values
/actuator/mappings Request-to-handler method mappings
/actuator/loggers Runtime log levels per package/class
/actuator/threaddump JVM thread dump
/actuator/httptrace Last 100 HTTP requests (if enabled)
/actuator/auditevents Audit events in the system

Not all endpoints are enabled or exposed by default.

Example:

When you open:

[Link]

You’ll see something like:


{
"status": "UP"
}

That means your app is running fine.


If it says "DOWN", then something went wrong.

How to Use It (Step by Step):

Step 1: Add it to your app

In your [Link] file:

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Step 2: Allow endpoints to be visible

In [Link]:

[Link]=*

This means: "Show me all the Actuator URLs."

Step 3: Run your app

Start the app, and open this in your browser:

[Link]

Is It Safe?

By default, not all info is shown to protect your app.


In real (production) apps, you can:

 Lock it with passwords


 Show only specific endpoints

SPRING BOOT BUILD SYSTEMS:

In Spring Boot, build systems are tools that help manage dependencies, compile source code,
package applications, and automate development tasks
(Example 1: A build system helps you build, package, and manage your Spring Boot project.
Think of it like a kitchen that takes raw ingredients (your code) and prepares a finished meal (a
working app).

With a build system, you can:

 Add libraries (dependencies)


 Compile your code
 Run tests
 Create a final .jar or .war file to run your app

Example 2: Imagine you're baking a cake 🍰:

 You need ingredients (libraries)


 You follow steps (compilation)
 You bake the cake (build your app)

A build system does all of this for your Spring Boot project:

 Adds the libraries your app needs (called dependencies)


 Compiles the code
 Runs tests (optional)
 Packages the app into a .jar file (Java program you can run))

Spring Boot Supports Two Main Build Systems:

1. ✅ Maven

Maven is the most popular build tool for Java and Spring Boot projects.

📄 Uses a file called [Link]

This file tells Maven:

 Which dependencies to download


 How to build the app
 What Java version to use

📄 Example [Link] file:


<project>
<modelVersion>4.0.0</modelVersion>
<groupId>[Link]</groupId>
<artifactId>myapp</artifactId>
<version>0.0.1-SNAPSHOT</version>

<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>

This tells Maven: “I want to build a Spring Boot web app.”

📄 Build and Run Commands:


mvn clean install # Builds the project
mvn spring-boot:run # Runs the app

✅Maven Pros:

 Easy for beginners


 Well-documented
 Lots of community support

2. ✅ Gradle

Gradle is a more modern and faster build tool than Maven.

📄 Uses a file called [Link] (or [Link] for Kotlin)

This file also tells Gradle what to do, like:

 Add dependencies
 Build settings
 How to run the app

📄 Example [Link] file (Groovy syntax):


plugins {
id '[Link]' version '3.2.0'
id '[Link]-management' version '1.1.0'
id 'java'
}

group = '[Link]'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

dependencies {
implementation '[Link]:spring-boot-starter-web'
}

This does the same job as Maven but in a simpler, more flexible format.
Build and Run Commands:
gradle build # Builds the project
gradle bootRun # Runs the app

Gradle Pros:

 Faster builds (uses caching)


 Less typing
 More powerful scripting

🔍 Quick Comparison: Maven vs Gradle


Feature Maven Gradle

File name [Link] [Link]

Language used XML Groovy or Kotlin

Learning curve Easy Slightly harder for beginners

Build speed Slower Faster

Community Larger Growing fast

Flexibility Less flexible More flexible

 Spring Boot supports two main build systems: Maven and Gradle

 Both do the same job: add dependencies, build, and run your app

 Maven is easier for beginners and very popular

 Gradle is faster and more flexible

SPRING BOOT CODE STRUCTURE:


Code is structured following conventional patterns that promote readability, scalability, and modularity.

When you create a Spring Boot application, it gives you a standard folder and file structure to
keep everything organized.

Think of it like a well-organized house:


 👉 The house (project folder)
 👉 Rooms (folders like controller, service, model, etc.)
 👉 Furniture (files like Java classes, configuration, etc.)

Typical Spring Boot Project Structure:

my-springboot-app/
├── src/
│ └── main/
│ ├── java/
│ │ └── com/
│ │ └── example/
│ │ └── myapp/
│ │ ├── [Link] <-- Main class
│ │ ├── controller/ <-- Web layer (APIs)
│ │ ├── service/ <-- Business logic
│ │ └── model/ <-- Data classes
│ └── resources/
│ ├── [Link] <-- App settings
│ ├── static/ <-- HTML, CSS, JS
│ └── templates/ <-- Thymeleaf views
├── test/ <-- Unit tests
├── [Link] or [Link] <-- Build file

1. [Link]

This is the main class with the main() method.


It’s where the Spring Boot app starts running.

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

2. controller/ folder

Contains controller classes that handle HTTP requests (like GET, POST).

@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
3. service/ folder

This is where you write business logic — the core functionality of your app.

@Service
public class UserService {
public String getUserName() {
return "John Doe";
}
}

The controller can call this service to get data.

4. model/ folder

Contains data classes, often called POJOs or entities.

public class User {


private String name;
private int age;

// Getters and setters


}

If you're using a database, you might annotate it with @Entity.

5. resources/[Link]

This file contains configuration settings for your app.

Example:

[Link]=8081
[Link]=jdbc:mysql://localhost:3306/mydb

You can also use [Link] if you prefer YAML format.

6. resources/static/

Place static files like:

 [Link]
 Images
 JavaScript
 CSS

These are served directly by the web server.

7. resources/templates/

Contains HTML templates if you use Thymeleaf or another template engine.

Example:

templates/
└── [Link]

8. test/ folder

This folder holds your unit tests and integration tests.

Example:

@SpringBootTest
class MyAppApplicationTests {
@Test
void contextLoads() {
}
}

9. [Link] or [Link]

These are your build tool files:

 [Link] is for Maven


 [Link] is for Gradle

They contain dependencies (libraries) and project settings.

Summary
Folder/File Purpose
Folder/File Purpose

[Link] Main app starter class

controller/ Handles web/API requests

service/ Business logic lives here

model/ Data structure (POJOs)

resources/[Link] App configuration

resources/static/ Static web files

resources/templates/ HTML templates for views

test/ Tests for your code

[Link] / [Link] Build configuration

SPRING BOOT RUNNERS:


In Spring Boot, runners are special components that allow you to execute code at application startup—
after the Spring context has been initialized.

In a Spring Boot application, you usually start your app using the main() method.

But what if you want to run some code automatically when the app starts?

For example:

 Initialize some data in the database


 Print a message
 Run a task once at startup

Two Main Runner Interfaces in Spring Boot:


Runner Type Description

CommandLineRunner Runs code after the app starts, and gets command-line arguments
Runner Type Description

ApplicationRunner Also runs code after the app starts, but gets more structured input

1. CommandLineRunner – Simple and Common

Use this if you want to run some logic right after the app starts.

Example:
import [Link];
import [Link];

@Component
public class MyStartupRunner implements CommandLineRunner {

@Override
public void run(String... args) {
[Link]("App has started! Running some startup logic...");
}
}

📄 What’s happening:

 @Component tells Spring to manage this class.


 run() method runs automatically when the app starts.
 args can capture command-line arguments (optional).

2. ApplicationRunner – Slightly More Advanced

This is similar to CommandLineRunner but gives better access to the application


environment.

Example:
import [Link];
import [Link];
import [Link];

@Component
public class MyAppRunner implements ApplicationRunner {

@Override
public void run(ApplicationArguments args) {
[Link]("Running with arguments: " +
[Link]());
}
}

What’s happening:

 You get access to [Link]() and other helpful methods.


 Useful for reading command-line options like --username=admin.

What's the Difference?


Feature CommandLineRunner ApplicationRunner

Simplicity Very simple A bit more flexible

Input type String array (String...) Structured arguments (ApplicationArguments)

When it runs After app starts Same (after app starts)

Where to Use Runners?

 Load default data into your database


 Call an API once when the app starts
 Check configurations or startup values
 Print startup logs

 Runners are used to run code automatically after your Spring Boot app starts
 Two main types:
o CommandLineRunner – simple
o ApplicationRunner – more advanced
 You just need to implement one of these interfaces and use @Component

What is a LOGGER?

A logger is like a notebook your app uses to write down messages while it runs.
These messages help you:

 Understand what your app is doing


 Debug problems
 Monitor performance

How to Use Logger in Spring Boot

Spring Boot uses SLF4J (Simple Logging Facade for Java) with Logback as the default logging
framework.

Example:
import [Link];
import [Link];
import [Link];

@Service
public class MyService {

private static final Logger logger =


[Link]([Link]);

public void doSomething() {


[Link]("Starting task...");
[Link]("Debugging info");
[Link]("This is a warning!");
[Link]("Something went wrong!");
}
}

Logging Levels:

Level What it means


TRACE Very detailed logs (not used often)
DEBUG Developer-level details
INFO General information
WARN Something unexpected, but not breaking
ERROR Something failed!

Configure in [Link]:
[Link]=INFO
[Link]=DEBUG
[Link]=[Link]
Building RESTful Web Services in Spring Boot (in Simple Language)

💡 What is a RESTful Web Service?

A REST API (or RESTful web service) lets two applications talk over the internet using
HTTP (like browsers and websites).

For example:

 A mobile app asks your Spring Boot app: “Give me all users.”
 Your app replies with user data in JSON format.

🔍 Basic Parts of a REST API


HTTP Method What it does Example

GET Get data /users

POST Create new data /users

PUT Update existing data /users/1

DELETE Delete data /users/1

Steps to Create REST API in Spring Boot

Step 1: Create a Spring Boot Project

Use [Link]
Add:

 Spring Web
 Spring Boot DevTools (optional)

Step 2: Create a Model Class


public class User {
private Long id;
private String name;
private String email;
// Getters and setters
}

Step 3: Create a Controller


import [Link].*;
import [Link].*;

@RestController
@RequestMapping("/users")
public class UserController {

private List<User> users = new ArrayList<>();

@GetMapping
public List<User> getAllUsers() {
return users;
}

@PostMapping
public String createUser(@RequestBody User user) {
[Link](user);
return "User added!";
}

@PutMapping("/{id}")
public String updateUser(@PathVariable Long id, @RequestBody User
newUser) {
for (User user : users) {
if ([Link]().equals(id)) {
[Link]([Link]());
[Link]([Link]());
return "User updated!";
}
}
return "User not found!";
}

@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) {
[Link](u -> [Link]().equals(id));
return "User deleted!";
}
}

Test the API

You can test it using:

 Postman (GUI)
 curl (command line)
 Swagger (if you add it)

Summary

Logger:

 Used to print messages to help with debugging and monitoring


 Uses [Link](), [Link](), etc.
 Configurable in [Link]

RESTful Web Services:

 Allow your Spring Boot app to communicate over the web


 Built using @RestController, @GetMapping, @PostMapping, etc.
 Uses JSON for sending and receiving data

REST CONTROLLER:

A Rest Controller is a special Spring Boot class that handles HTTP requests (like GET,
POST, PUT, DELETE) and returns data (usually JSON) to whoever called it.

Think of it as a waiter in a restaurant:

 You (the client) ask for something (send a request)


 The waiter (Rest Controller) takes your order (processes the request)
 The waiter brings back your food (response with data)

How to Create a Rest Controller?

Step 1: Use @RestController Annotation

This tells Spring Boot:


"This class will handle REST API calls and send JSON responses."

Step 2: Map URLs with Annotations

 @GetMapping — for GET requests (read data)


 @PostMapping — for POST requests (create data)
 @PutMapping — for PUT requests (update data)
 @DeleteMapping — for DELETE requests (delete data)
Example: Simple Rest Controller
import [Link].*;

import [Link];
import [Link];

@RestController
@RequestMapping("/api/users") // Base URL for all methods in this controller
public class UserController {

private List<String> users = new ArrayList<>();

// GET /api/users
@GetMapping
public List<String> getAllUsers() {
return users;
}

// POST /api/users
@PostMapping
public String addUser(@RequestBody String user) {
[Link](user);
return "User added!";
}

// DELETE /api/users/{index}
@DeleteMapping("/{index}")
public String deleteUser(@PathVariable int index) {
if (index >= 0 && index < [Link]()) {
[Link](index);
return "User removed!";
}
return "Invalid index!";
}
}

Explanation:

1. Imports
import [Link].*;
import [Link];
import [Link];

 These imports bring in Spring annotations needed to create a REST controller.


 ArrayList and List are standard Java classes to manage collections (lists) of objects.

2. Class Declaration
@RestController
@RequestMapping("/api/users") // Base URL for all methods in this controller
public class UserController {

 @RestController tells Spring this class handles REST API requests and will return
JSON responses (not HTML).
 @RequestMapping("/api/users") means all URLs inside this class will start with
/api/users.

So, if you have a method with @GetMapping, its full URL becomes /api/users.

3. Data Storage
private List<String> users = new ArrayList<>();

 This is a simple list to store user names as Strings.


 It acts like a temporary database — data is lost when the app restarts.
 In a real app, you'd use a database instead.

4. GET Method to Get All Users


@GetMapping
public List<String> getAllUsers() {
return users;
}

 @GetMapping means this method will respond to HTTP GET requests at /api/users.
 When a client (like Postman or a browser) calls GET /api/users, this method returns the
full list of users.
 Spring automatically converts the List<String> to JSON so the client gets something
like:

["Alice", "Bob", "Charlie"]

5. POST Method to Add a User


@PostMapping
public String addUser(@RequestBody String user) {
[Link](user);
return "User added!";
}

 @PostMapping means this method handles HTTP POST requests to /api/users.


 @RequestBody String user means the method expects the request body to contain a
string (the new user's name).
 The new user name is added to the users list.
 The method returns a simple confirmation message "User added!".
 Example request body (sent as raw text or JSON string):
"David"

6. DELETE Method to Remove a User by Index


@DeleteMapping("/{index}")
public String deleteUser(@PathVariable int index) {
if (index >= 0 && index < [Link]()) {
[Link](index);
return "User removed!";
}
return "Invalid index!";
}

 @DeleteMapping("/{index}") means this method handles HTTP DELETE requests


to URLs like /api/users/2.
 @PathVariable int index grabs the index value from the URL path.
 It checks if the index is valid (inside the list bounds).
 If valid, it removes the user at that position in the list.
 Returns "User removed!" if successful.
 If invalid index, returns "Invalid index!".
 For example, sending a DELETE request to /api/users/1 removes the second user (list
is zero-based).

Summary of What This Controller Does:


HTTP
URL Action Example Response
Method

GET /api/users Returns all users ["Alice", "Bob"]

Adds a new user (name in


POST /api/users "User added!"
body)

"User removed!" or "Invalid


DELETE /api/users/{index} Deletes user by index
index!"

What Happens Behind the Scenes?

 Spring Boot scans this class because of @RestController.


 When the server receives a request matching /api/users + HTTP method, it calls the
corresponding method.
 Java objects are converted to/from JSON automatically.
 You manage data in-memory using a simple list.
What’s Happening Here?
Part Explanation

@RestController Marks the class as a REST API controller

@RequestMapping Sets the base URL for all methods

@GetMapping Handles HTTP GET requests (fetch data)

@PostMapping Handles HTTP POST requests (add data)

@DeleteMapping Handles HTTP DELETE requests (remove data)

@RequestBody Reads JSON data from the request body

@PathVariable Gets data from the URL path (e.g., {index})

Why Use @RestController Instead of @Controller?

 @RestController automatically converts your Java objects into JSON (or XML) to
send as a response.
 @Controller is used mostly when you want to return HTML views (web pages).

Summary:

 Rest Controller = Spring class for handling REST API requests.


 Annotate your class with @RestController.
 Use @GetMapping, @PostMapping, etc., to map URLs to methods.
 Methods return Java objects, which Spring automatically converts to JSON.
 Use @RequestBody to get data from the client, and @PathVariable to get parts of the
URL.
REQUEST MAPPING: In Spring Boot, @RequestMapping is a powerful and flexible annotation
used to map web requests (HTTP requests) to specific controller methods. It’s part of Spring MVC,
which is included by default in Spring Boot when you build a web application.

 Request mapping = connecting URLs to methods

 It helps your app know what to do when someone visits a certain page or sends data

What is @RequestMapping in Spring Boot?

@RequestMapping is used in controller classes to define how HTTP requests should be handled.

For example:

@RestController
@RequestMapping("/api")
public class HelloController {

@RequestMapping("/hello")
public String sayHello() {
return "Hello from Spring Boot!";
}
}

This maps an HTTP request to /api/hello to the sayHello() method.

How It Works in Spring Boot

Spring Boot uses Spring MVC under the hood. When a request hits the application, Spring
looks at the controller classes and their mapping annotations (like @RequestMapping) to figure
out which method to invoke.

🔍 @RequestMapping – Common Attributes


Attribute Description

value or path URL path(s) to match

method HTTP method (GET, POST, etc.)

params Query parameter conditions


Attribute Description

headers Header-based conditions

consumes Content-Type of incoming request

produces Content-Type of response

🔍 Examples

1. Basic GET Mapping


@RequestMapping(value = "/greet", method = [Link])
public String greet() {
return "Hello!";
}

2. Mapping with Path Variable


@RequestMapping(value = "/user/{id}", method = [Link])
public String getUser(@PathVariable("id") Long userId) {
return "User ID: " + userId;
}

3. Mapping with Query Parameters


@RequestMapping(value = "/search", params = "q", method = [Link])
public String search(@RequestParam("q") String query) {
return "Searching for: " + query;
}

4. Mapping POST with JSON


@RequestMapping(value = "/addUser", method = [Link], consumes =
"application/json")
public String addUser(@RequestBody User user) {
return "User added: " + [Link]();
}

⚡ Shorthand Annotations in Spring Boot

Spring Boot encourages using more readable shorthand annotations introduced in Spring 4+:

Annotation Equivalent
Annotation Equivalent

@GetMapping @RequestMapping(method = GET)

@PostMapping @RequestMapping(method = POST)

@PutMapping @RequestMapping(method = PUT)

@DeleteMapping @RequestMapping(method = DELETE)

@GetMapping("/users")
public List<User> getAllUsers() {
return [Link]();
}

REQUEST BODY:
What is @RequestBody in Spring Boot?

@RequestBody is used when your app needs to receive data from the user (client) in the body
of the request, usually in JSON format.

You're building an app that takes a form where someone sends their name and age.

But instead of filling a form on a website, they send the info using an HTTP POST request like
this:

{
"name": "Ali",
"age": 25
}

Spring Boot can take this data and automatically put it into a Java object using @RequestBody.

🔍 Real Example:

Step 1: Create a Java class to hold the data


public class Person {
private String name;
private int age;
// Getters and Setters
public String getName() { return name; }
public void setName(String name) { [Link] = name; }

public int getAge() { return age; }


public void setAge(int age) { [Link] = age; }
}

Step 2: Create a controller to receive the data


@RestController
public class PersonController {

@PostMapping("/person")
public String receivePerson(@RequestBody Person person) {
return "Hello " + [Link]() + ", you are " + [Link]() +
" years old.";
}
}

🔍 How It Works:

If someone sends a POST request to:

[Link]

With this JSON body:

{
"name": "Ali",
"age": 25
}

Spring Boot will automatically:

 Read the JSON 👉


 Create a Person object 👉
 Fill in name = Ali and age = 25 👉
 Run the receivePerson() method and return a message 👉

🔍 Why Use @RequestBody?

 It makes handling JSON easy.


 You don’t need to manually read or parse the request.
 It connects your data with Java classes directly.
"@RequestBody helps your app read data sent by users and turn it into a Java object that you can
work with."

PATH VARIABLE:

In Spring Boot, @PathVariable is used to extract values from the URI path and bind them to method
parameters in controller methods. It’s commonly used in RESTful web services where resources are
accessed via dynamic paths.

In Spring Boot, the term PATH variable usually refers to the part of a URL that contains
dynamic values. These are used in REST APIs to send information through the URL itself.

💡 Example:

Let's say you build a REST API to get a user by their ID.

@GetMapping("/user/{id}")
public String getUserById(@PathVariable String id) {
return "User ID is: " + id;
}

 The {id} is the PATH variable.


 If someone accesses [Link]
the method will be called with id = "42".

 PATH variable = a placeholder in the URL that can change.


 It lets you pass data through the URL itself.
 Spring Boot grabs that value using @PathVariable.

💡 Quick Comparison:

URL What Spring Boot sees


/user/1 @PathVariable id = "1"
/product/abc123 @PathVariable code = "abc123"
What are REQUEST PARAMETERS?

Request Parameters are key-value pairs sent in the URL (usually in GET requests), after the
question mark ?.

They are often used to filter, search, or customize results.

Example URL with Request Parameters:


[Link]

 query=shoes → This is one request parameter


 sort=price → This is another request parameter

How to Handle Request Parameters in Spring Boot

Use the @RequestParam annotation in your controller method.

Example 1: Basic Usage


@GetMapping("/search")
public String searchItems(@RequestParam String query, @RequestParam String
sort) {
return "Searching for: " + query + ", Sorted by: " + sort;
}

👉 If the URL is:

[Link]

👉 Output:

Searching for: shoes, Sorted by: price

💡 Example 2: Optional Parameters (with default value)


@GetMapping("/search")
public String searchItems(@RequestParam String query,
@RequestParam(defaultValue = "relevance") String
sort) {
return "Searching for: " + query + ", Sorted by: " + sort;
}
👉 If the URL is:

[Link]

➡️ It works! Because sort has a default value: "relevance"

💡 Example 3: Optional Parameters (can be missing)

@GetMapping("/search")
public String searchItems(@RequestParam String query,
@RequestParam(required = false) String sort) {
return "Searching for: " + query + ", Sorted by: " + (sort != null ? sort
: "default");
}

This allows sort to be missing entirely.

💡 Example 4: Multiple Values (List)


@GetMapping("/filter")
public String filterItems(@RequestParam List<String> category) {
return "Filtering by: " + category;
}

👉 URL:

[Link]

👉 Output:

Filtering by: [shoes, hats]

🔍 Summary
Term Meaning

@RequestParam Gets data from the URL after ?

required=true Default, param must be present

required=false Param is optional


Term Meaning

defaultValue Use this value if the param is missing

List params Use List<Type> if multiple values are passed

Use Case Example


@GetMapping("/products")
public String getProducts(@RequestParam String category,
@RequestParam(required = false, defaultValue =
"10") int limit) {
return "Category: " + category + ", Showing top " + limit + " results.";
}

👉 URL:

[Link]

👉 Output:

Category: clothing, Showing top 10 results.

What are HTTP Methods?

They define the action you want to perform on a resource (like a user, product, or article) in a
REST API.

Method Purpose

GET Read (fetch data)

POST Create (add new data)

PUT Update (replace existing data)

DELETE Delete (remove data)

🔍 1. GET – Fetch data

✅ Use Case: Get a user by ID


@RestController
public class UserController {

@GetMapping("/users/{id}")
public String getUser(@PathVariable String id) {
return "Getting user with ID: " + id;
}
}

👉 Call this with:

GET [Link]

👉 Response:

Getting user with ID: 101

🔍 2. POST – Create new data

✅ Use Case: Add a new user


@RestController
public class UserController {

@PostMapping("/users")
public String createUser(@RequestBody String userData) {
return "Creating user with data: " + userData;
}
}

👉 Call with POST request body:

{
"name": "Alice",
"email": "alice@[Link]"
}

👉 Response:

Creating user with data: {"name":"Alice","email":"alice@[Link]"}

🔍 3. PUT – Update existing data

✅ Use Case: Update a user by ID


@RestController
public class UserController {

@PutMapping("/users/{id}")
public String updateUser(@PathVariable String id, @RequestBody String
userData) {
return "Updating user " + id + " with data: " + userData;
}
}

👉 Call with:

PUT [Link]

Request Body:

{
"name": "Alice Updated",
"email": "alice_new@[Link]"
}

👉 Response:

Updating user 101 with data: {"name":"Alice


Updated","email":"alice_new@[Link]"}

🔍 4. DELETE – Remove data

✅ Use Case: Delete a user by ID


@RestController
public class UserController {

@DeleteMapping("/users/{id}")
public String deleteUser(@PathVariable String id) {
return "Deleting user with ID: " + id;
}
}

👉 Call:

DELETE [Link]

👉 Response:

Deleting user with ID: 101

🔍 Summary Table
HTTP Method Annotation Purpose Requires Body? URL Example

GET @GetMapping Read/Get data ❌ No /users/1


HTTP Method Annotation Purpose Requires Body? URL Example

POST @PostMapping Create data ✅ Yes /users

PUT @PutMapping Update data ✅ Yes /users/1

DELETE @DeleteMapping Delete data ❌ No /users/1

🔍 Real-Life Example (User API)


@RestController
@RequestMapping("/users")
public class UserController {

@GetMapping("/{id}")
public String getUser(@PathVariable String id) { return "Getting user " +
id; }

@PostMapping
public String createUser(@RequestBody String data) { return "Creating
user: " + data; }

@PutMapping("/{id}")
public String updateUser(@PathVariable String id, @RequestBody String
data) {
return "Updating user " + id + ": " + data;
}

@DeleteMapping("/{id}")
public String deleteUser(@PathVariable String id) {
return "Deleting user " + id;
}
}

BUILDING WEB APPLICATIONS in Spring Boot is one of its core strengths. Let me walk
you through how to build a web application using Spring Boot, in a simple and clear way —
from setup to working endpoints.

What You’ll Learn

1. ✅ What you need


2. ✅ Project structure
3. ✅ Step-by-step guide
4. ✅ Example: Mini Web App (User Manager)
5. ✅ How to run it
1. What You Need

 Java (17+ preferred)


 Maven or Gradle
 Spring Boot (latest version)
 An IDE like IntelliJ, Eclipse, or VS Code

2. Project Structure (Simple Spring Boot Web App)


pgsql
CopyEdit
springboot-webapp/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/example/webapp/
│ │ │ ├── [Link]
│ │ │ ├── controller/
│ │ │ │ └── [Link]
│ │ │ ├── model/
│ │ │ │ └── [Link]
│ │ │ └── service/
│ │ │ └── [Link]
│ │ └── resources/
│ │ ├── [Link]
│ │ └── templates/
│ │ └── [Link] ← (if using Thymeleaf)
└── [Link]

3. Step-by-Step Guide

Step 1: Create a Spring Boot Project

Use [Link]

Choose:

 Project: Maven
 Dependencies:
o Spring Web
o Thymeleaf (optional, for HTML views)
o Spring Boot DevTools (for auto-restart)
Step 2: Main Application Class
@SpringBootApplication
public class WebAppApplication {
public static void main(String[] args) {
[Link]([Link], args);
}
}

Step 3: Model Class ([Link])


public class User {
private String name;
private String email;

// Getters and Setters


}

Step 4: Controller ([Link])


@RestController
@RequestMapping("/users")
public class UserController {

List<User> users = new ArrayList<>();

@GetMapping
public List<User> getUsers() {
return users;
}

@PostMapping
public String addUser(@RequestBody User user) {
[Link](user);
return "User added successfully!";
}
}

Step 5: (Optional) Thymeleaf View

In resources/templates/[Link]:

<!DOCTYPE html>
<html xmlns:th="[Link]
<head><title>Home</title></head>
<body>
<h1>Welcome to Spring Boot Web App</h1>
</body>
</html>
And create a controller:

@Controller
public class PageController {
@GetMapping("/")
public String homePage() {
return "home"; // maps to [Link]
}
}

4. Run Your App

Use your IDE or the command line:

mvn spring-boot:run

Or:

java -jar target/[Link]

Now open:

 [Link] — see user list (empty at first)


 POST to /users with JSON to add users
 [Link] — view HTML page (if using Thymeleaf)

🔍 Summary
Part What It Does

@RestController Creates web API endpoints

@RequestMapping Maps URLs to methods

@GetMapping Handles GET requests

@PostMapping Handles POST requests

Thymeleaf Renders HTML templates

[Link] Configures port, view settings, etc.

You might also like