Thursday, June 11, 2026

Introduction to Spring Boot and Spring MVC

0. Introduction

Client–Server Architecture

The client–server architecture is a distributed application structure that divides workloads between service providers (servers) and service consumers (clients).

  • A service is an abstraction over computing resources.
  • A server hosts one or more server programs and exposes services to clients.
  • Clients request services and servers process those requests.
  • The most common communication stack is TCP/IP.
  • Examples of client–server applications include email systems, network printing systems, and the World Wide Web.

Client–Server Communication

Clients and servers exchange messages using a request–response communication pattern.

  • A protocol is a set of rules that allows computers to communicate.
  • The client sends a request.
  • The server processes the request and returns a response.
  • The client interprets the response according to the protocol.
  • Servers often expose an Application Programming Interface (API), which defines how clients can access a service.

World Wide Web

The World Wide Web is built on top of the HTTP protocol.

HTTP

HTTP (Hypertext Transfer Protocol) is:

  • Stateless.
  • Text-based.
  • Request–response oriented.
  • Based on the client–server model.

Because HTTP is stateless, every request is independent from previous requests.
HTTP was created in conjunction with HTML standard.

HTML

HTML (HyperText Markup Language):

  • Describes the structure of web pages.
  • Allows documents to contain links to other documents.
  • Allows documents to reference images, videos and other media content. The browser then retrieves those resources through additional HTTP requests.

Web Browsers

End users access the World Wide Web through web browsers. A web browser sends HTTP requests to web servers in order to retrieve web resources identified by URLs. These resources include HTML documents, images, videos, style sheets, and other content that the browser interprets and displays to the user.

URLs

A URL (Uniform Resource Locator) is a name that identifies the location of a resource on a network.

General format:

protocol://host:port/path/file

Example:

http://www.football.com:80/leagues/premier_league_2020.html

Components:

  • Protocol: http
  • Host: www.football.com
  • Port: 80
  • Path: /leagues/
  • Resource: premier_league_2020.html
 

HTTP Endpoints

An endpoint is an HTTP interface exposed by a web application through which clients send HTTP requests. An endpoint is typically identified by the combination of an HTTP method (such as GET or POST) and a URL path. It serves as the entry point through which external clients invoke the application's functionality.

For example, GET /home and POST /home are two different endpoints because they handle different kinds of requests.

In a Spring MVC application, an endpoint is the combination of:

  • a URL (e.g. /customers/500)
  • an HTTP method (GET, POST, PUT, DELETE, etc.)
  • any additional request conditions (headers, content type, etc.)
  • the controller method that handles the request

For example:

@RequestMapping("/customers")
public class CustomerController {

    @GetMapping("/{id}")
    public Customer getCustomer(@PathVariable Long id) {
        ...
    }
}

Route (or Request Mapping)

A route is a server-side mechanism that maps an incoming HTTP request to the the code that should handle it.

When a request reaches a Spring application application, Spring matches the request to the appropriate endpoint and invokes the corresponding controller method.

Relationship between route and endpoint

For example,

@GetMapping("/home")
public String home() {
    return "home";
}
  • Endpoint → what the client sees ("I send a request to /home")
  • Route → what the server uses internally ("Requests to /home are handled by home()")
 

MIME Types

HTTP can transport many different kinds of data, and the sender tells the receiver what kind of data it is by specifying a MIME type such as plain text (plain/text), HTML (text/html), JSON (application/json), JPEG images (image/jpeg), PNG images (image/png) or PDF files (application/pdf).

The MIME type is sent in the HTTP Content-Type header. For example: Content-Type: text/html or Content-Type: application/json.

1. What Is a Web Application?

A web application is software accessed through a web browser.

A web application consists of:

  • Front-End (Client Side). It runs inside the browser. Its responsibilities includes: displaying user interfaces, capturing user input and sending requests to the back-end. It uses technologies such as HTML, CSS and JavaScript

  • Back-End (Server Side). It runs on application servers. Its responsibilities includes: processing requests, executing business logic, accessing databases and generating responses. A back-end application serves many users simultaneously. Multiple requests may execute concurrently, so server-side applications must be designed to handle concurrent execution safely.


URL vs URI

A URI (Uniform Resource Identifier) identifies a resource.

A URL is a specific type of URI that also specifies how to locate the resource. For examples, https://example.com/users/10 is both a URI and a URL. A URL is a type of URI, a URI is not always a URL.

In modern REST APIs, developers commonly refer to endpoint paths as URIs.


Different Ways to Implement Web Applications

There are two different approaches to design web application

Traditional Web Applications

  • There is no front-end back-end separation
  • The back-end serves a complete view in response to each client request.
  • The server returns data formats such as HTML, CSS, JavaScript and images.

  • Workflow:

    Browser --> Request --> Server
    Browser <-- HTML page <-- Server
      

    Examples: Spring MVC with Thymeleaf, JSP applications

Modern Web Applications

  • The front-end and back-end are separated.
  • The browser runs a JavaScript front-end application, loaded from the server at the first request.
  • The front-end application calls APIs and receives raw data in JSON or XML formats
  • The front-end interprets the data and dinamically renders the user interface.

  • Workflow:

    Browser --> API Request --> Server
    Browser <-- JSON/XML <-- Server
      

    Examples: React/Angular/Vue with a Spring Boot REST API.


Using a Servlet Container

What Is a Servlet Container?

A servlet container:

  • Receives HTTP requests.
  • Converts HTTP messages into Java objects.
  • Executes servlets.
  • Sends HTTP responses.

Popular servlet containers are: Apache Tomcat, Jetty, Undertow.

What Is a Servlet?

A servlet is a Java class managed by the servlet container. The container invokes servlet methods and provides HttpServletRequest and HttpServletResponse objects.

Developing with Servlets

  • Suppose you are developing the back-end of a web application. To handle requests sent to a specific URL path, you create a servlet and configure the servlet container to associate that path with the servlet.
  • For example, if a client sends requests to the path /home/person/edit, you can create a servlet responsible for handling those requests. In the web.xml deployment descriptor, you register the servlet class com.example.view.PersonEditServlet and bind it to the path /home/person/edit:

    <servlet>
      <servlet-name>PersonEdit</servlet-name>
      <servlet-class>com.example.view.PersonEditServlet</servlet-class>
    </servlet>

    <servlet-mapping>
      <servlet-name>PersonEdit</servlet-name>
      <url-pattern>/home/person/edit</url-pattern>
    </servlet-mapping>

  • As the application grows and more URL paths are added, the developer typically has to create and configure additional servlets, making the application harder to maintain.


Spring Web Applications and the Dispatcher Servlet

A Spring MVC application does not require developers to create servlets for every endpoint. Instead, Spring registers a single servlet, the DispatcherServlet. The DispatcherServlet acts as the application's Front Controller.

Every HTTP request follows this path:

Client
   ↓
Tomcat
   ↓
DispatcherServlet
   ↓
Controller
   ↓
View / Response

This design is known as the Front Controller Pattern.


2 Spring Boot

How to Use Spring Boot for Developing a Web Application

  • Developing a traditional Spring web application typically requires configuring a servlet container and creating and configuring servlets to handle the different requests that clients may send.
  • Spring Boot simplifies web application development by eliminating most manual configuration through auto-configuration and embedded server support.

Spring Boot provides three main features:

  • Project Initialization Service: generates a pre-configured project skeleton.
  • Dependency Starters: provide groups of compatible dependencies for specific capabilities, such as web development, data access or security.
  • Auto-Configuration: automatically configures the application based on the dependencies present in the project, supplying sensible default settings that can be customized when necessary. Auto-configuration creates Spring beans automatically when appropriate beans are not already defined by the application.

Using the Project Initialization Service

Spring Boot provides a project initialization service called Spring Initializr, which generates a ready-to-use Spring Boot project. Many IDEs integrate directly with Spring Initializr. Alternatively, the service can be accessed through a web browser at: https://start.spring.io/

To generate a project:

  1. Select the project settings, such as the build tool (Maven or Gradle), programming language (Java, Kotlin, or Groovy), Spring Boot version, and Java version.
  2. Specify the project coordinates, including the groupId, artifactId, project name, package name, and packaging type (JAR or WAR).
  3. Select the dependencies required by the application, such as Spring Web, Spring Data JPA, Spring Security, or Thymeleaf.
  4. Click Generate to download the project archive.
  5. Extract the archive and open the project in an IDE.

The initialization service generates an empty but fully configured Spring Boot application. The generated project typically contains:

  • A build configuration file (pom.xml for Maven or build.gradle for Gradle).
  • A main application class annotated with @SpringBootApplication, which serves as the application's entry point.
  • An application.properties (or application.yml) configuration file.
  • A standard project directory structure for source code, resources, and tests.

The generated project can be executed immediately, providing a foundation on which the application's functionality can be implemented.


What Is in the Preconfigured pom.xml File?

Spring Initializr generates a preconfigured POM file containing three important elements:

1. Spring Boot Parent POM

The generated project inherits from the Spring Boot parent POM:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>4.1.0</version>
</parent>

The Spring Boot parent POM provides:

  • Compatible versions for Spring and third-party libraries.
  • Dependency management, reducing the need to specify versions explicitly.
  • Default Maven plugin configuration commonly used in Spring Boot projects.

As a result, developers can add dependencies without worrying about version compatibility.

2. Dependencies

The POM contains the dependencies selected when the project was generated.

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Many Spring Boot dependencies are starters. A starter is a collection of compatible libraries that provides a specific capability.
Note: as the project inherits from the Spring Boot parent POM, starter dependencies usually do not require an explicit version number.

3. Spring Boot Maven Plugin

The generated POM also contains the Spring Boot Maven plugin:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

This plugin integrates Spring Boot with Maven and provides features such as:

  • Packaging the application as an executable JAR.
  • Running the application directly from Maven.
  • Including all required dependencies inside the packaged application.

Using Dependency Starters

A dependency starter is a predefined collection of compatible dependencies that provides a specific application capability. Instead of manually selecting and configuring individual libraries, developers declare a dependency on a starter and Spring Boot automatically includes the required libraries.

For example, to develop a web application, a project can declare a dependency on the Spring MVC starter:

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

By adding this starter, Spring Boot includes the libraries required for web development, such as Spring MVC and Embedded Tomcat. As a result: java -jar application.jar starts a web server directly without installing Tomcat separately.

Dependency starters are available for many common capabilities, including: Web application development, Database access, Data persistence with JPA, Application security, Testing.

When a project requires a capability, the developer simply adds the corresponding starter dependency to the POM file. Spring Boot then manages the individual libraries and their versions.

Starter dependencies offer two important advantages:

  • Simplified dependency management: developers add a single dependency instead of many individual libraries.
  • Version compatibility: Spring Boot provides a set of tested and compatible library versions, reducing dependency conflicts.

Note: By convention, the artifact identifier of a starter begins with: spring-boot-starter-*.

Note: Without dependency starters, developers would need to identify, add, and maintain all required libraries manually, while also ensuring that their versions are compatible with one another.


Spring Boot Auto-Configuration

Spring Boot applies the Convention over Configuration principle. Instead of requiring developers to configure every component explicitly, Spring Boot automatically configures the application using sensible default settings.

Auto-configuration analyzes the dependencies present in the project and configures the corresponding Spring components automatically. As a result, developers can focus on implementing application functionality rather than writing infrastructure configuration. Auto-configuration creates Spring beans automatically when appropriate beans are not already defined by the application.

Dependency starters and auto-configuration work together:

  • Dependency starters declare the capabilities required by the application.
  • Auto-configuration configures those capabilities using default settings.

Example 1: Spring Web

When the project includes spring-boot-starter-web, Spring Boot automatically configures the components commonly required by web applications using sensible default settings, including the DispatcherServlet, Handler Mapping, View Resolver, and an embedded Tomcat server. When the application starts, Spring Boot automatically launches the embedded Tomcat server and listens on port 8080 by default.

The default configuration provided by Spring Boot can be customized whenever necessary. Developers can override the convention by defining their own configuration properties or Spring beans.

Auto-configuration significantly reduces the amount of configuration code required to develop Spring applications while still allowing full control when custom behavior is needed.

In summary:

Starter Dependency  →  Provides the libraries
Auto-Configuration  →  Configures the libraries

3 Creating a Web Application with Spring MVC

This section introduces the basic architecture of a Spring web application using Spring MVC.

A simple web application consists of:

  1. A web page that is displayed to the user.
  2. A controller that handles HTTP requests and returns the appropriate web page.

To create the application, you:

  1. Start from an empty Spring Boot project with spring web starter dependency
  2. Create an HTML page.
  3. Create a Spring MVC controller that maps a URL to that page.

3.1 Step 1: Create an HTML Page

Create a file named home.html in the static/ directory.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home Page</title>
</head>
<body>
    <h1>Welcome!</h1>
</body>
</html>

This page contains the content that will be returned to the client when the application receives a request for the home page.


3.2 Step 2: Create a Spring MVC Controller

What is a Spring MVC Controller?

A Spring MVC controller is a component responsible for handling incoming HTTP requests and generating responses.

A controller contains one or more handler methods (also called action methods), each of which is executed when a specific URL is requested. Each handler method typically corresponds to one endpoint.

Creating a Controller

To define a controller, annotate a class with @Controller.

@Controller
public class MainController {
    ...
}

The @Controller annotation marks the class as a Spring-managed component, allowing Spring to detect it and register it as a bean in the application context.

Creating Controller Actions

Annotate the controller method with @RequestMapping and specify the URL path that should be mapped to that method. Other synonyms of URL path are request path and endpoint path.

For example:

@RequestMapping("/home")
public String home() {
    return "home.html";
}

When a client sends a request to /home:

  1. Spring MVC routes the request to the home() method.
  2. The method may execute business logic if necessary.
  3. The method returns the name of the page that should be sent back to the client.

Complete Controller Example

@Controller
public class MainController {

    @RequestMapping("/home")
    public String home() {
        return "home.html";
    }
}

In this example, the MainController handles requests sent to /home and returns the home.html page as the response.


More Specific Request Mappings

Instead of @RequestMapping, Spring provides:

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping

Example:

@GetMapping("/home")
public String home() {
    return "home";
}

These make the supported HTTP method explicit.


The Spring MVC Request Processing Flow

When a client requests:

http://localhost:8080/home

the following steps occur:

  1. Browser sends HTTP request.
  2. Tomcat receives the request.
  3. Tomcat forwards the request to DispatcherServlet.
  4. DispatcherServlet asks Handler Mapping to locate a matching controller action.
  5. The controller action executes.
  6. The action returns a logical view name.
  7. DispatcherServlet asks View Resolver to locate the actual view.
  8. The view is rendered.
  9. DispatcherServlet sends the response through Tomcat.
  10. Browser displays the response.

Diagram:

Browser
   ↓
Tomcat
   ↓
DispatcherServlet
   ↓
HandlerMapping
   ↓
Controller
   ↓
ViewResolver
   ↓
HTML View
   ↓
Browser

Note: Spring Boot already prepared the Spring MVC components for you. You only have to write controller actions and map them to requests using annotations.


Additional Modern Spring MVC Concept: @RestController

When building REST APIs, Spring applications usually use @RestController instead of @Controller. The @Controller returns views (HTML pages), whereas the @RestController returns data directly (JSON/XML).

Example:

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello!";
    }
}

Response:

Hello!

without rendering a view.

No comments:

Post a Comment