Introduction to Forms
Learn how to use HTML forms in the application.
We'll cover the following...
As an example of how to use HTML forms, we’ll create a user in the UI.
Form fields
Implementing a form submission is a multi-phase process:
- The browser uses
GET
to display the form. - The user enters information using the form elements.
- The browser uses
POST
with the form elements’ information. - If there are no validation errors, the browser gets redirected to avoid double submissions.
- If there are validation errors, the form remains in place so the user can correct the information.
The below diagram shows the success flow of the process.
Success flow of the form submission process
Mapping form inputs to object properties
As a first implementation step, we need to create an object that will map each HTML form input to a property of the Java object:
Press + to interact
package com.tamingthymeleaf.application.user.web;import com.tamingthymeleaf.application.user.CreateUserParameters;import com.tamingthymeleaf.application.user.Gender;import com.tamingthymeleaf.application.user.PhoneNumber;import com.tamingthymeleaf.application.user.UserName;import org.springframework.format.annotation.DateTimeFormat;import javax.validation.constraints.Email;import javax.validation.constraints.NotBlank;import javax.validation.constraints.NotNull;import javax.validation.constraints.Pattern;import java.time.LocalDate;public class CreateUserFormData {@NotBlankprivate String firstName;@NotBlankprivate String lastName;@NotNullprivate Gender gender;@NotBlankprivate String email;@NotNull@DateTimeFormat(pattern = "yyyy-MM-dd")private LocalDate birthday;@NotBlank@Pattern(regexp = "[0-9.\\-() x/+]+")private String phoneNumber;// Getters and setters omitted}
Compared to the CreateUserParameters
object that uses rich value objects, here we mainly restrict ourselves to String
types and no nesting (like with UserName
). This will make it easier to map ...