Spring Boot CRUD Application with Thymeleaf

Spring Boot CRUD Application with Thymeleaf

TECHNOLOGY

11/28/20234 min read

Introduction

In this blog post, we will delve into the world of Spring Boot and Thymeleaf by exploring a CRUD (Create, Read, Update, Delete) example code. We will discuss the concepts behind Spring Boot and Thymeleaf, and how they work together to create a powerful and efficient web application.

What is Spring Boot?

Spring Boot is a framework built on top of the Spring framework that simplifies the development of Java applications. It provides a set of opinionated defaults and auto-configuration options, reducing the need for manual configuration. Spring Boot aims to make it easy to create stand-alone, production-grade Spring-based applications with minimal effort.

What is Thymeleaf?

Thymeleaf is a modern server-side Java template engine for web and standalone environments. It is designed to be a natural and intuitive way to create dynamic web pages using Java. Thymeleaf templates can be used with Spring Boot to generate HTML that is rendered on the client side.

Setting Up the Project

To follow along with this example, make sure you have Java and Maven installed on your machine. You can create a new Spring Boot project by using the Spring Initializr, which provides a convenient way to generate the project structure and dependencies.

Once you have generated the project, open it in your preferred Java IDE. The project structure should include a main class annotated with @SpringBootApplication, which serves as the entry point for your application.

Creating the Model

In our CRUD example, let's assume we are building a simple web application to manage a collection of books. We will start by creating a Book class that represents the model for our application.


public class Book {
    private Long id;
    private String title;
    private String author;
    // getters and setters
}

Creating the Repository

Next, we need to create a repository interface that will handle the CRUD operations for our Book model. In Spring Boot, this is typically done by extending the JpaRepository interface provided by Spring Data JPA.


public interface BookRepository extends JpaRepository {
}

Creating the Controller

The controller is responsible for handling the incoming HTTP requests and returning the appropriate response. In our example, we will create a BookController class with methods for handling the CRUD operations.


@Controller
@RequestMapping("/books")
public class BookController {
    private BookRepository bookRepository;

    public BookController(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    @GetMapping("/")
    public String getAllBooks(Model model) {
        List books = bookRepository.findAll();
        model.addAttribute("books", books);
        return "book-list";
    }

    @GetMapping("/new")
    public String showCreateForm(Model model) {
        model.addAttribute("book", new Book());
        return "book-form";
    }

    @PostMapping("/new")
    public String createBook(@ModelAttribute("book") Book book) {
        bookRepository.save(book);
        return "redirect:/books/";
    }

    @GetMapping("/{id}/edit")
    public String showEditForm(@PathVariable("id") Long id, Model model) {
        Optional book = bookRepository.findById(id);
        model.addAttribute("book", book.orElseThrow(() -> new IllegalArgumentException("Invalid book Id:" + id)));
        return "book-form";
    }

    @PostMapping("/{id}/edit")
    public String updateBook(@PathVariable("id") Long id, @ModelAttribute("book") Book book) {
        book.setId(id);
        bookRepository.save(book);
        return "redirect:/books/";
    }

    @GetMapping("/{id}/delete")
    public String deleteBook(@PathVariable("id") Long id) {
        bookRepository.deleteById(id);
        return "redirect:/books/";
    }
}

Creating the Views

Now that we have our model, repository, and controller in place, we can create the views using Thymeleaf templates. In our example, we will create two templates: book-list.html and book-form.html.

The book-list.html template will display a table of all the books in our collection:


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Book List</title>
</head>
<body>
    <h1>Book List</h1>
    <table>
        <tr>
            <th>Title</th>
            <th>Author</th>
            <th>Actions</th>
        </tr>
        <tr th:each="book : ${books}">
            <td th:text="${book.title}"></td>
            <td th:text="${book.author}"></td>
            <td>
                <a th:href="@{/books/{id}/edit(id=${book.id})}">Edit</a>
                <a th:href="@{/books/{id}/delete(id=${book.id})}">Delete</a>
            </td>
        </tr>
    </table>
    <a th:href="@{/books/new}">Add New Book</a>
</body>
</html>

The book-form.html template will handle both the creation and editing of books:


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Book Form</title>
</head>
<body>
    <h1>Book Form</h1>
    <form th:action="@{/books/new}" th:object="${book}" method="post">
        <input type="text" th:field="*{title}" placeholder="Title" /><br/>
        <input type="text" th:field="*{author}" placeholder="Author" /><br/>
        <input type="submit" value="Save" />
    </form>
</body>
</html>

Running the Application

With everything in place, you can now run the Spring Boot application. Open a terminal or command prompt, navigate to the project directory, and run the following command:


mvn spring-boot:run

Once the application is running, you can access it by opening a web browser and navigating to http://localhost:8080/books/. You should see the book list page, where you can add, edit, and delete books.

Conclusion

In this blog post, we explored a CRUD example code using Spring Boot and Thymeleaf. We discussed the concepts behind Spring Boot and Thymeleaf, and how they work together to create a powerful and efficient web application. By following the steps outlined in this blog post, you should now have a good understanding of how to build a basic CRUD application using these technologies.

Remember, this is just a starting point, and there is much more to learn about Spring Boot and Thymeleaf. I encourage you to explore the official documentation and experiment with different features and configurations to further enhance your web development skills.