Spring MVC Forms tags and Data Binding

 Thymeleaf is a powerful Java template engine used for rendering web pages in Spring applications. It provides specific form tags to easily bind form data to Java objects. This is especially useful in Spring MVC, where form submissions are processed and bound to model objects in the controller.

In Spring, data binding refers to the automatic process of binding data from a form to a model object, which is then used by the controller to process the data.

Here’s a breakdown of how to handle form tags and data binding with Thymeleaf and Spring MVC.


πŸ”‘ Key Concepts

  1. Form Tags in Thymeleaf: Thymeleaf provides a set of form-specific tags such as <form>, <input>, <label>, and others to create and manage forms.
  2. Data Binding: This refers to the automatic binding of form data to Java objects when a form is submitted. In Spring, this is done using @ModelAttribute in the controller.

🧩 Step-by-Step Example: Using Forms and Data Binding with Thymeleaf in Spring


πŸ“„ 1. Create the Model Class

This class will represent the form data submitted by the user. For example, we will use a User model class.

User.java

package com.example.demo.model; public class User { private String name; private String email; private int age; // 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; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }

This User class contains basic fields like name, email, and age, which we’ll bind to the form inputs.


πŸ“„ 2. Create the Controller

In the controller, we will create a method to display the form (with a GET request) and a method to process the submitted form (with a POST request).

UserController.java

package com.example.demo.controller; import com.example.demo.model.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ModelAttribute; @Controller public class UserController { // Display the form @GetMapping("/user-form") public String showForm(Model model) { model.addAttribute("user", new User()); // Create a new empty User object to bind the form data return "user-form"; // Return the form view (Thymeleaf template) } // Handle the form submission @PostMapping("/user-form") public String submitForm(@ModelAttribute("user") User user) { // Here, Spring will automatically bind the form data to the "user" object System.out.println("Name: " + user.getName()); System.out.println("Email: " + user.getEmail()); System.out.println("Age: " + user.getAge()); // Return the result view after form submission return "form-result"; } }
  • @ModelAttribute("user"): This annotation tells Spring to bind the form data to the User object.
  • @GetMapping("/user-form"): This method displays the form to the user.
  • @PostMapping("/user-form"): This method handles the form submission and processes the data.

πŸ“„ 3. Create the Thymeleaf Form Template

In the form template (user-form.html), we will use Thymeleaf’s form tags to bind the form inputs to the User object.

user-form.html

<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>User Registration Form</title> </head> <body> <h2>User Registration</h2> <!-- Form to bind the User object --> <form th:action="@{/user-form}" th:object="${user}" method="post"> <!-- Name field --> <label for="name">Name:</label> <input type="text" th:field="*{name}" id="name" /> <!-- Email field --> <label for="email">Email:</label> <input type="text" th:field="*{email}" id="email" /> <!-- Age field --> <label for="age">Age:</label> <input type="number" th:field="*{age}" id="age" /> <!-- Submit button --> <button type="submit">Submit</button> </form> </body> </html>
  • th:action: Specifies the action URL for the form submission (it will post to /user-form).
  • th:object: Binds the form to the user object (from the model).
  • th:field="*{name}": Automatically binds the form field to the name property of the user object.
    • th:field handles both the binding and validation.

πŸ“„ 4. Create the Form Result Template

After the form is submitted, we will display the submitted form data in a separate view (form-result.html).

form-result.html

<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Form Submission Result</title> </head> <body> <h2>Form Submitted Successfully!</h2> <p>Name: <span th:text="${user.name}"></span></p> <p>Email: <span th:text="${user.email}"></span></p> <p>Age: <span th:text="${user.age}"></span></p> </body> </html>
  • ${user.name}, ${user.email}, and ${user.age}: These expressions display the values from the User object after form submission.

πŸ“„ 5. Application Properties (Optional)

You may configure some basic settings like the application port.

application.properties

server.port=8080

πŸš€ Running the Application

  1. Start the Spring Boot application.
  2. Navigate to http://localhost:8080/user-form in your browser to see the user registration form.
  3. Fill out and submit the form.
  4. After submitting, you will see the form data displayed in the result view (form-result.html).

πŸ” Key Concepts in Thymeleaf Form Handling

  1. th:object: Specifies the model object to bind the form data to. In this case, it's the User object.
  2. th:field: Binds individual form fields to the properties of the model object (e.g., name, email, age).
    • It automatically binds the form data to the model object and supports form validation and error handling.
  3. Data Binding:
    • The @ModelAttribute in the controller handles the binding of form data to the model object (User).
    • Spring automatically populates the fields of the User object with the submitted form data.

Summary

  • Thymeleaf Form Tags: Use th:object for binding the entire form to a model object and th:field to bind each individual form field.
  • Data Binding: Spring automatically binds form data to Java objects when using @ModelAttribute in the controller.
  • Controller: Handles form rendering and form submission processing.

Comments