Handling Forms in Spring Boot: Thymeleaf and Spring Forms

Handling Forms in Spring Boot: Thymeleaf and Spring Forms

Spring Boot is a popular framework for building web applications, and it seamlessly integrates with Thymeleaf, a modern server-side Java template engine for web and standalone environments. In this article, we’ll explore how to handle forms in Spring Boot using Thymeleaf and Spring Forms, complete with examples to illustrate the concepts.

Introduction to Spring Boot and Thymeleaf

Spring Boot simplifies the development of Java web applications by providing a framework that handles a lot of the boilerplate code. Thymeleaf is a templating engine that integrates well with Spring Boot, making it easy to build dynamic web pages.

Setting Up Your Spring Boot Project

To get started, you need to set up a Spring Boot project. You can do this using Spring Initializr or your favorite IDE.

Dependencies

Make sure to include the following dependencies in your pom.xml file:

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

Creating a Simple Form

Let’s create a simple form that collects user information such as name and email.

Step 1: Create the Model

First, create a simple model class to hold the form data.

public class User {
    private String name;
    private String email;

    // Getters and setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Step 2: Create the Controller

Next, create a controller to handle the form submission.

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class UserController {

    @GetMapping("/userForm")
    public String showForm(Model model) {
        model.addAttribute("user", new User());
        return "userForm";
    }

    @PostMapping("/userForm")
    public String submitForm(@ModelAttribute User user, Model model) {
        model.addAttribute("user", user);
        return "userResult";
    }
}

Step 3: Create the Thymeleaf Template for the Form

Create a Thymeleaf template named userForm.html to display the form.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>User Form</title>
</head>
<body>
    <h1>User Form</h1>
    <form th:action="@{/userForm}" th:object="${user}" method="post">
        <div>
            <label>Name:</label>
            <input type="text" th:field="*{name}" />
        </div>
        <div>
            <label>Email:</label>
            <input type="email" th:field="*{email}" />
        </div>
        <div>
            <button type="submit">Submit</button>
        </div>
    </form>
</body>
</html>

Step 4: Create the Thymeleaf Template for the Result

Create another Thymeleaf template named userResult.html to display the submitted form data.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>User Result</title>
</head>
<body>
    <h1>User Information</h1>
    <p>Name: <span th:text="${user.name}"></span></p>
    <p>Email: <span th:text="${user.email}"></span></p>
</body>
</html>

Running the Application

Run your Spring Boot application and navigate to http://localhost:8080/userForm in your browser. You should see the user form. Fill out the form and submit it to see the result.

Advanced Form Handling

Form Validation

Spring Boot and Thymeleaf also support form validation. To add validation, include the Hibernate Validator dependency in your pom.xml:

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

Modify the User model to include validation annotations:

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;

public class User {
    @NotEmpty(message = "Name is required")
    private String name;

    @NotEmpty(message = "Email is required")
    @Email(message = "Email should be valid")
    private String email;

    // Getters and setters
}

Update the controller to handle validation errors:

import org.springframework.validation.BindingResult;

@Controller
public class UserController {

    @GetMapping("/userForm")
    public String showForm(Model model) {
        model.addAttribute("user", new User());
        return "userForm";
    }

    @PostMapping("/userForm")
    public String submitForm(@Valid @ModelAttribute User user, BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            return "userForm";
        }
        model.addAttribute("user", user);
        return "userResult";
    }
}

Update the form template to display validation errors:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>User Form</title>
</head>
<body>
    <h1>User Form</h1>
    <form th:action="@{/userForm}" th:object="${user}" method="post">
        <div>
            <label>Name:</label>
            <input type="text" th:field="*{name}" />
            <div th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</div>
        </div>
        <div>
            <label>Email:</label>
            <input type="email" th:field="*{email}" />
            <div th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Email Error</div>
        </div>
        <div>
            <button type="submit">Submit</button>
        </div>
    </form>
</body>
</html>

Conclusion

Handling forms in Spring Boot with Thymeleaf is straightforward and powerful. This article covered the basics of creating forms, handling form submissions, and adding validation. By leveraging these tools, you can build robust and user-friendly web applications.

Tags

#SpringBoot #Thymeleaf #SpringForms #Java #WebDevelopment #FormHandling #FormValidation #SpringMVC #JavaDevelopment #Programming #SoftwareDevelopment

Leave a Reply