Introduction to Forms

Learn how to use HTML forms in the application.

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:

  1. The browser uses GET to display the form.
  2. The user enters information using the form elements.
  3. The browser uses POST with the form elements’ information.
  4. If there are no validation errors, the browser gets redirected to avoid double submissions.
  5. 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
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 {
@NotBlank
private String firstName;
@NotBlank
private String lastName;
@NotNull
private Gender gender;
@NotBlank
@Email
private 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 ...