Spring Boot: your first web application in Java

Lesson 1 of 3 · Spring Boot

Spring Boot is the most popular tool for making web applications and services in Java. The program becomes a server: it waits for requests from a browser or another application and returns a response – an HTML page or data in JSON form. In this lesson you create a project, start the server and write your first addresses (routes) that return text and JSON.

Before you start: what you need to know first – collections and records, lambda expressions, web basics (HTTP, URL).
How to learn: work in your own project step by step, and after each step start the server and check the result in the browser. The examples are for Spring Boot 3 or 4 and Java 17+; type each piece of code into the file named in the comment at the top of the example.

What Spring and Spring Boot are

Spring is a set of libraries for server applications: handling web requests, working with a database, security (user login), sending emails… Spring Boot makes it easy to get started: it sets up most things by itself and builds a web server (Tomcat) into the application, so the application starts like an ordinary Java program.

TermMeaning
servera program that waits for requests on a port (Spring Boot: 8080)
route (endpoint)an address the server responds to, e.g. /hello
controllera class whose methods handle requests for certain routes
JSONa text format for data: {"name": "Ana", "grade": 7}
annotationa label with @ (e.g. @GetMapping) that tells Spring what a class or method is

Before this lesson you should know classes and objects, collections and the basic ideas of the web (Web basics: request, response, URL, HTTP methods).

Creating a project: start.spring.io

You need JDK 17 or newer (recommended: 21) and a development environment – the easiest is IntelliJ IDEA Community. The project is created on the site start.spring.io (Spring Initializr):

FieldValue
ProjectMaven
LanguageJava
Spring Bootthe latest stable version (without SNAPSHOT/M/RC)
Grouprs.svetprogramiranja
Artifacttasks
PackagingJar
Java21 (or 17)
DependenciesSpring Web (we add more later)

The Generate button downloads a zip. Unpack it and open the folder in IntelliJ (File → Open); the environment downloads the libraries it needs by itself (the first time this takes a few minutes).

tasks/
├── pom.xml                      ← list of libraries (dependencies) and Maven settings
├── mvnw, mvnw.cmd               ← Maven wrapper: running without installing Maven separately
└── src/
    ├── main/
    │   ├── java/rs/svetprogramiranja/tasks/
    │   │   └── TasksApplication.java    ← the main class (the main method)
    │   └── resources/
    │       ├── application.properties   ← application settings
    │       ├── static/                  ← HTML, CSS, JS and images the server sends as they are
    │       └── templates/               ← page templates (if they are used)
    └── test/                            ← automatic tests

The main class and starting the application

The Initializr creates the main class. The @SpringBootApplication annotation turns on automatic configuration and the search for components (controllers, services) in this package and its subpackages.

// src/main/java/rs/svetprogramiranja/tasks/TasksApplication.java
package rs.svetprogramiranja.tasks;

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

@SpringBootApplication
public class TasksApplication {
    public static void main(String[] args) {
        // starts the built-in web server and the whole application
        SpringApplication.run(TasksApplication.class, args);
    }
}

The application is started with the green triangle next to the main method in IntelliJ, or from the command line (cmd) in the project folder:

mvnw.cmd spring-boot:run

The message Tomcat started on port 8080 appears in the console. For now every address returns a page with error 404 (Whitelabel Error Page) – no route exists yet. The server is stopped with the red square or with Ctrl+C.

The first controller: the /hello route

A controller is a class marked with @RestController. Every method marked with @GetMapping("/path") responds to a GET request for that path; whatever the method returns is sent to the browser.

// src/main/java/rs/svetprogramiranja/tasks/HelloController.java
package rs.svetprogramiranja.tasks;

import java.time.LocalTime;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    // http://localhost:8080/hello
    @GetMapping("/hello")
    public String hello() {
        return "Hello from Spring Boot! The time is " + LocalTime.now().withNano(0);
    }

    // a parameter from the query: http://localhost:8080/greeting?name=Ana
    @GetMapping("/greeting")
    public String greeting(@RequestParam(defaultValue = "stranger") String name) {
        return "Hello, " + name + "!";
    }

    // part of the path as a parameter: http://localhost:8080/square/12
    @GetMapping("/square/{n}")
    public long square(@PathVariable long n) {
        return n * n;
    }
}

After changing the code the server must be restarted. Then open the three addresses from the comments in the browser. @RequestParam reads a value from the part of the address after ?, and @PathVariable the part of the path in curly brackets. Spring converts the text "12" into a number by itself.

Returning data as JSON

When a controller method returns an object (for example a record) or a list, Spring automatically converts it into JSON. This is how a server makes data for JavaScript in the browser or for a mobile application:

// src/main/java/rs/svetprogramiranja/tasks/InfoController.java
package rs.svetprogramiranja.tasks;

import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class InfoController {

    // record: the fields become keys in the JSON
    public record Lesson(int number, String title, boolean done) { }

    // http://localhost:8080/lessons
    @GetMapping("/lessons")
    public List<Lesson> lessons() {
        return List.of(
                new Lesson(1, "First web application", true),
                new Lesson(2, "REST API", false),
                new Lesson(3, "Database", false));
    }
}

The browser shows the response:

[{"number":1,"title":"First web application","done":true},
 {"number":2,"title":"REST API","done":false},
 {"number":3,"title":"Database","done":false}]

application.properties and static pages

Settings are written in src/main/resources/application.properties, for example a different port if 8080 is busy:

# src/main/resources/application.properties
spring.application.name=tasks
server.port=8081

Files in the src/main/resources/static folder are sent to the browser unchanged. If you create index.html there, it is shown at the address http://localhost:8080/. On that page JavaScript can ask the controller for data:

<!-- src/main/resources/static/index.html -->
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Lessons</title></head>
<body>
  <h1>My lessons</h1>
  <ul id="list"></ul>
  <script>
    // asks the server for JSON and makes the list items
    fetch("/lessons")
      .then(response => response.json())
      .then(lessons => {
        for (const l of lessons) {
          const li = document.createElement("li");
          li.textContent = l.number + ". " + l.title + (l.done ? " ✔" : "");
          document.getElementById("list").appendChild(li);
        }
      });
  </script>
</body>
</html>

This is the same division of work as in every web application: the frontend (HTML, CSS, JS – see the HTML, CSS and JavaScript course) shows the data, and the backend (Spring Boot) provides it.

Practice tasks

Each task has a hint and a solution.

TASK 01Difficulty: easy

A calculator as a web service

Add a CalculatorController with the routes:

  • /sum?a=5&b=7 returns 12;
  • /factorial/{n} returns n! as a number of type long (for n ≤ 20);
  • /divisors/{n} returns the list of divisors of n as a JSON array, e.g. [1,2,3,6] for 6.
Common mistakes and tips
  • After every change to the Java code restart the server (or add the Spring Boot DevTools dependency, which does it by itself).
  • Controllers must be in the same package as the main class or in one of its subpackages – otherwise Spring does not find them and you get error 404.
  • The error "Port 8080 was already in use" means that the server is already running (perhaps in another window) – stop it or change server.port.
  • The address is case-sensitive: /Hello is not the same as /hello.

Check your knowledge

Open the quiz

Spring Boot – the basics

1. What does the annotation @GetMapping("/hello") do?




2. On which port does a Spring Boot application run by default?




3. What does Spring do with an object returned by a controller method?




4. How do you read the value from the address /greeting?name=Ana in a method?