Activity 1

Create a Spring Boot Application

Build a Spring Boot application from scratch and create a simple REST controller that responds to HTTP requests with messages.

⏱ Duration: 45 minutes #SpringBoot #SpringInitializr #REST #HTTP #Hands-On

Activity Overview

In this activity you will create a Spring Boot application from scratch using Spring Initializr. You will import the project into your IDE, examine the generated project structure, run the application, and then create a simple Spring MVC controller.

The controller will respond to different HTTP GET requests with simple text messages. This activity introduces the fundamental relationship between a browser, an HTTP request, a Spring controller, and an HTTP response.

What you will build

An application called Library Borrowing System. In this activity you will start with one resource which is the books resource with endpoints such as /api/v1/books. You will test them directly from a web browser.

Learning Goals

By the end of this activity, you should be able to:
  • Create a Spring Boot project using Spring Initializr.
  • Identify the main components of a basic Spring Boot project.
  • Explain the purpose of the @SpringBootApplication annotation.
  • Create a controller using @RestController.
  • Map an HTTP GET request using @GetMapping.
  • Return a simple message as an HTTP response.
  • Test HTTP endpoints using a web browser.

Prerequisites

  • Java 17 or later installed, verify with java -version.
  • IntelliJ IDEA IDE.
  • A stable internet connection for downloading Spring dependencies.
  • Basic knowledge of Java classes and methods.

Before You Start: The HTTP Request–Response Cycle

A web application communicates using HTTP. When you enter a URL into a browser, the browser sends an HTTP request to the server. Spring Boot receives the request and determines which controller method should handle it.

Spring Boot Request Flow
Figure A2.1 Basic HTTP Request–Response Cycle
Component Role
Browser Sends an HTTP request.
URL Identifies the resource or endpoint being requested.
@RestController Tells Spring that the class handles HTTP requests and returns response data.
@GetMapping Maps an HTTP GET request to a Java method.
Return value Becomes the body of the HTTP response.

Topics Covered

#Topic
1Spring Initializr
2Spring Boot project structure
3@SpringBootApplication
4@RestController
5@GetMapping
6HTTP GET requests
7Testing endpoints in a browser

Step-by-Step Instructions

1 Generate the Spring Boot Project

Open your browser and navigate to https://start.spring.io.

Use the following settings:

FieldValue
ProjectGradle – Groovy
LanguageJava
Spring BootUse the current stable 3.x release available in Spring Initializr
Groupcom.mycompany
Artifactlibrary-system
Namelibrary-system
DescriptionSimple Spring Boot HTTP Controller
Package namecom.mycompany.librarysystem
PackagingJar
Java17

Click ADD DEPENDENCIES and add:

  • Spring Web

Click GENERATE to download the project ZIP file.

Spring Initializr Configuration
Figure A2.2 Spring Initializr Configuration

2 Extract and Open the Project

  1. Locate library-system.zip in your Downloads folder.
  2. Extract the ZIP file.
  3. Open the extracted project in IntelliJ IDEA IDE.
  4. Allow Gradle to import the project and download its dependencies.
  5. Wait until the project is fully synchronized before continuing.
Note

Do not create the project folders manually. Spring Initializr has already created the Gradle wrapper, source folders, configuration files, and test structure for you.

3 Examine the Project Structure

Confirm that your project has a structure similar to this:

library-system/ ├── build.gradle ├── settings.gradle ├── gradlew ├── gradlew.bat ├── gradle/ │ └── wrapper/ └── src/ ├── main/ │ ├── java/ │ │ └── com/example/librarysystem/ │ │ └── LibrarySystemApplication.java │ └── resources/ │ └── application.properties └── test/ └── java/ └── com/example/librarysystem/ └── LibrarySystemApplicationTests.java

Locate the main application class:

package com.example.librarysystem;

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

@SpringBootApplication
public class LibrarySystemApplication {

    public static void main(String[] args) {
        SpringApplication.run(LibrarySystemApplication.class, args);
    }
}
Key Idea

@SpringBootApplication identifies the main Spring Boot application class. The call to SpringApplication.run() starts the Spring application and its embedded web server.

Let us examine the components of the project structure :
FileDescription
build.gradleGradle build file that defines dependencies and build tasks.
settings.gradleGradle settings file that defines the project name.
gradlew and gradlew.batGradle wrapper scripts for Unix/Linux and Windows.
gradle/wrapper/Contains the Gradle wrapper JAR and properties file.
src/main/java/Contains the main Java source code.
src/main/resources/Contains the main resource files.
application.propertiesConfiguration file for Spring Boot application properties.
src/test/java/Contains the test Java source code.

4 Review the Spring Web Dependency

Open build.gradle which contains the Gradle build configuration including the list of dependencies that your project requires. Scroll down and find the Spring Web dependency. It should contain something similar to:

dependencies {
                implementation 'org.springframework.boot:spring-boot-starter-web'

                testImplementation 'org.springframework.boot:spring-boot-starter-test'
            }

The spring-boot-starter-web dependency provides the infrastructure needed to build web applications and REST-style HTTP endpoints with Spring Boot.

Important

Later on we will add other dependencies such as database, JPA, H2, Lombok, and so on. In this activity, we are intentionally keeping the first controller application as small as possible.

5 Configure the Application Port

Open: src/main/resources/application.properties

This file contains the configuration properties for the Spring Boot application, such as which port the application uses, database settings, etc. Add the following:

spring.application.name=library-system
                    server.port=8080

The first property gives the application a name. The second tells Spring Boot to listen for HTTP requests on port 8080.

6 Create the Controller class

Inside: src/main/java/com/example/librarysystem

Create a new class named:

BookController

Your structure should now look like:

src/main/java/com/example/librarysystem/ ├── LibrarySystemApplication.java └── BooksController.java

In the BooksController.java file, enter the following code:


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BooksController {

    @GetMapping("api/v1/books")
    public String getBooks() {
        return "Here is the List of books";
    }
}

Study the code carefully.

Code Purpose
@RestController Marks the class as a controller whose methods handle HTTP requests and return response data.
@GetMapping("api/v1/books") Maps an HTTP GET request for api/v1/books to the method below it.
public String getBooks() Defines the Java method that handles the request.
return "Here is the List of books"; Returns the text that will be sent in the HTTP response body.
Observe the URL

Notice the /api prefix. In larger applications, API endpoints are often grouped under a common URL prefix such as /api. /v1 indicates the version of the API. This allows for future versions of the API to coexist with older versions.

8 Run the Application

You can run the application with Intellij IDEA by clicking the "Run" button. In this activity, we will learn how to run the application using commands in the terminal. You can use the windows command prompt or PowerShell terminal by running "cmd" command in windows search bar. You can also use the terminal in IntelliJ IDEA by clicking the "Terminal" tab at the bottom of the IDE as shown in the figure.

How to Open Terminal in IntelliJ IDEA
Figure A1.3 How to Open Terminal in IntelliJ IDEA

Navigate to the project root directory where build.gradle is located.

./gradlew bootRun

On Windows:

gradlew.bat bootRun

Watch the console. You should eventually see a message similar to:

Started LibrarySystemApplication in X.XXX seconds
Success

Your Spring Boot application is now running and listening for HTTP requests on port 8080.

9 Test Your First HTTP Endpoint

Recall that these URL endpoints can be called by other applications or tools. In particular, most of the time they will be called by a web browser. You can test the endpoint by opening a web browser and entering the following URL:

http://localhost:8080/api/v1/books
Domain name

Since we do not have a real server yet, and hence we are not using a real domain name, we will use localhost to refer to our own computer. localhost is a special domain name that refers to the computer you are currently using. It is used to test applications running on your own machine.

By default this will make an HTTP request with a GET method. We will learn more about other HTTP methods later. You should see:

Browser displaying the response
Figure A1.4 Browser displaying the response to http://localhost:8080/api/v1/books HTTP GET request

You have just created your first Spring Boot HTTP endpoint.

Trace the request

Browser → GET api/v1/booksBooksController.getBooks() → returned String → HTTP response → Browser

10 Add a Second Endpoint

Now modify BooksController and add a second method:

@GetMapping("api/v1/welcome")
public String welcome() {
    return "Welcome to my Spring Boot application!";
}

The complete controller should now contain two endpoints:

package com.example.librarysystem.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BooksController {

    @GetMapping("api/v1/books")
    public String getBooks() {
        return "Here is the List of books";
    }

    @GetMapping("api/v1/welcome")
    public String welcome() {
        return "Welcome to my Spring Boot application!";
    }
}

Test the new endpoint:

http://localhost:8080/api/v1/welcome

You should receive: Welcome to my Spring Boot application!

11 Create an Endpoint with a Path Variable

Next, create an endpoint that uses part of the URL as input. To do this, you will use a path variable. A path variable is a placeholder in the URL that can be replaced with actual values when making a request. In the code, you will use @PathVariable annotation to extract the value from the URL and pass it to the method.

Add this method to the controller class:

@GetMapping("api/v1/hello/{name}")
public String helloName(@PathVariable String name) {
    return "Hello, " + name + "!";
}

Test it with:

http://localhost:8080/api/v1/hello/Alice

The response should be:

Hello, Alice!

Try another name:

http://localhost:8080/api/v1/hello/Ali

The response should change accordingly:

Hello, Ali!
Key Concept

{name} is a path variable. Spring extracts the value from the URL and supplies it to the name parameter because of the @PathVariable annotation.

13 Test All Endpoints

Test each URL and record the response.

HTTP Method URL Expected Response
GET /api/v1/hello Hello from Spring Boot!
GET /api/v1/welcome Welcome to my Spring Boot application!
GET /api/v1/hello/Alice Hello, Alice!
GET /api/v1/hello/Ali Hello, Ali!

14 Stop the Application

Return to the terminal and press Ctrl+C. The embedded server will stop and the application will terminate.

What you have built

You created a Spring Boot application and connected four HTTP GET endpoints to Java methods. The browser sends the request, Spring maps it to a controller method, and the method produces the HTTP response.

Deliverables Checklist

Before You Finish , Check All Items

  • Project generated using Spring Initializr.
  • Spring Web dependency added.
  • Project imported into the IDE without errors.
  • Application starts successfully with Gradle.
  • HelloController created in the controller package.
  • @RestController used correctly.
  • @GetMapping used to map HTTP GET requests.
  • /hello returns a message.
  • /welcome returns a message.
  • /hello/{name} uses a path variable.
  • /api/v1/greeting returns a message.
  • All endpoints tested successfully in a browser.

Extension Challenge

Now add your own endpoint without copying an existing example.

Challenge

Create an endpoint named /about that returns a message containing your name and the name of your course.

For example, the endpoint could respond with:

Hello! My name is ______ and I am learning Spring Boot.

Then test it in your browser at:

http://localhost:8080/about
Do not copy the solution immediately

Try to create the method yourself. You should be able to determine which annotation is required, what URL should be mapped, and what the method should return.

Troubleshooting Guide

Problem Likely Cause Solution
404 Not Found URL does not match a controller mapping. Check the URL and the value in @GetMapping.
Controller is not detected Controller package is outside the application's component scan. Make sure the controller package is under com.example.hellospring.
Port 8080 was already in use Another application is using port 8080. Stop the other application or change server.port.
Application does not start Java or Gradle configuration problem. Check java -version, Gradle synchronization, and the terminal error.
Browser cannot connect Spring Boot application is not running. Start the application again with ./gradlew bootRun.
/hello/Alice does not work Missing or incorrect @PathVariable. Check both {name} in the URL mapping and the method parameter.

Reflection Questions

Answer the following questions in your own words:

  1. What is the purpose of @RestController?
  2. What is the difference between @RestController and a normal Java class?
  3. What does @GetMapping("/hello") do?
  4. What happens when a browser requests http://localhost:8080/hello?
  5. Why does the return value of the controller method appear in the browser?
  6. What is a path variable, and why is @PathVariable needed?
  7. What would happen if you requested /hello/Bob but the controller only defined /hello?

Up Next

Excellent work! You have now created your first Spring Boot controller and connected Java methods to HTTP GET requests.

In the next activity, you will move beyond simple text responses and learn how Spring Boot can return structured data such as JSON. You will begin to see how these endpoints form the foundation of a REST API.