Sebastian Gomez
Spring Boot Tutorial: Views and Controllers with Product Management
Hello, developers. In this tutorial we are going to build a Spring Boot application to manage products. You will learn to set up a project from scratch, create a home page, show a product list, detail individual products, and simulate product creation with form validation. Let's get to it.
Introduction
This tutorial will guide you step by step to build a Spring Boot application for managing products. We'll cover the following topics:
- Setting up a Spring Boot project.
- Creating a home page.
- Displaying a product list.
- Showing the details of a product.
- Simulating product creation with form validation.
By the end you'll have a working application that you can expand and improve.
Step 1: Creating the Spring Boot Project
### Option A: Using Spring Initializr (Recommended)
- Open Spring Initializr.
- Configure the project:
- Project: Maven - Language: Java - Spring Boot Version: the latest stable one Initializr offers you (today the 3.5.x line). - Group: com.docencia - Artifact: tutorial - Name: tutorial - Package Name: com.docencia.tutorial - Packaging: Jar - Java Version: pick the version installed on your system (check it with java -version).
- Add the dependencies:
- Spring Web (for REST endpoints). - Thymeleaf (for HTML templates). - Spring Boot Starter Validation (for form validation).
- Generate and download the project.
- Extract the ZIP file and open it in your favorite IDE (IntelliJ, Eclipse, etc.).
- Run the project:
./mvnw spring-boot:runThe application will be available at http://localhost:8080/.
Step 2: Creating the Home Page
### 1. Create the Home Controller
Create a file named HomeController.java in src/main/java/com/docencia/tutorial/controllers/:
package com.docencia.tutorial.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("title", "Bienvenido a Spring Boot");
model.addAttribute("subtitle", "Una aplicación Spring Boot de EAFIT");
return "home/index";
}
}### 2. Create the Home View
Create a file named index.html in src/main/resources/templates/home/:
<!DOCTYPE html>
<html lang="es" xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${title}"></title>
</head>
<body>
<h1 th:text="${subtitle}"></h1>
</body>
</html>Step 3: Listing Products
### 1. Create the Product Controller
Create a file named ProductController.java in src/main/java/com/docencia/tutorial/controllers/:
package com.docencia.tutorial.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.List;
import java.util.Map;
@Controller
public class ProductController {
private static final List<Map<String, String>> products = List.of(
Map.of("id", "1", "name", "TV", "description", "Mejor TV"),
Map.of("id", "2", "name", "iPhone", "description", "Mejor iPhone"),
Map.of("id", "3", "name", "Chromecast", "description", "Mejor Chromecast"),
Map.of("id", "4", "name", "Gafas", "description", "Mejores Gafas")
);
@GetMapping("/products")
public String index(Model model) {
model.addAttribute("title", "Productos - Tienda Online");
model.addAttribute("products", products);
return "product/index";
}
}### 2. Create the Product List View
Create a file named index.html in src/main/resources/templates/product/:
<!DOCTYPE html>
<html lang="es" xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${title}"></title>
</head>
<body>
<h2>Lista de Productos</h2>
<ul>
<li th:each="product : ${products}">
<span th:text="${product.name}"></span>
</li>
</ul>
</body>
</html>Step 4: Creating Products (Form Validation)
### 1. Add a Product Form Model
Let's create the form model in a model package, not inside controllers. Keeping models and DTOs separate from controllers is a good layering practice that will help you as the project grows. Create a file named ProductForm.java in src/main/java/com/docencia/tutorial/model/:
package com.docencia.tutorial.model;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
public class ProductForm {
@NotEmpty(message = "El nombre del producto es obligatorio")
private String name;
@NotNull(message = "El precio es obligatorio")
@Positive(message = "El precio debe ser un número positivo")
private Double price;
// Getters y Setters
}### 2. Display the Creation Form
Before we can submit the form we need a route that displays it. The view uses th:object="${productForm}", so the controller must add an empty productForm to the model. Add this handler to ProductController.java (remember to also import your new model):
import com.docencia.tutorial.model.ProductForm;
@GetMapping("/products/create")
public String create(Model model) {
model.addAttribute("productForm", new ProductForm());
return "product/create";
}Without this @GetMapping, visiting /products/create would throw an error because of the missing productForm attribute.
### 3. Update the Controller to Save the Product
Now modify ProductController.java to handle the form submission. Notice the imports: they are required for the snippet to compile without surprises.
import com.docencia.tutorial.model.ProductForm;
import jakarta.validation.Valid;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
@PostMapping("/products/save")
public String save(@Valid @ModelAttribute("productForm") ProductForm productForm,
BindingResult result, Model model) {
if (result.hasErrors()) {
return "product/create";
}
// Save logic (simulated)
return "redirect:/products";
}### 4. Create the Form View
Create a file named create.html in src/main/resources/templates/product/:
<form th:action="@{/products/save}" method="post" th:object="${productForm}">
<input type="text" th:field="*{name}" placeholder="Nombre del Producto" />
<input type="number" th:field="*{price}" placeholder="Precio" />
<button type="submit">Enviar</button>
</form>Step 5: Running the Application
### 1. Run the Spring Boot Application
./mvnw spring-boot:run### 2. Access the Application
- Home Page:
http://localhost:8080/ - Product List:
http://localhost:8080/products - Create Product:
http://localhost:8080/products/create
Conclusion
Congratulations. You've built a Spring Boot application that includes:
- A home page with Thymeleaf.
- A dynamic product listing.
- Form validation with Jakarta Validation.
- Simulated product creation.
Next Steps
How about connecting the application to a database using Spring Data JPA? Keep learning and building.
Suggested exercises
- Create a product detail page at
/products/{id}that shows the name and description of a specific product. - Replace the
List<Map<String, String>>with your ownProductclass with typed fields, and adapt the controller and the views. - Display the validation messages in
create.htmlusingth:errors="*{name}"andth:errors="*{price}", and check that they appear when you submit the empty form.
3-point summary
- A Spring Boot controller maps routes with
@GetMappingand@PostMappingand passes data to the Thymeleaf views through theModel. - Form validation relies on the Jakarta Validation annotations (
@NotEmpty,@NotNull,@Positive) together with@ValidandBindingResultin the controller. - Every form needs both a
@GetMappingthat displays it with an empty object in the model and a@PostMappingthat processes the submission.
I hope this tutorial was useful to you and that you can apply it to a project you have in mind. If you have any questions, don't hesitate to leave them in the comments, and if you liked it, you can also share it using the social links below. Happy coding.
Sebastian Gomez
Creador de contenido principalmente acerca de tecnología.