Spring Form Input

Include those in the dependencies. We need the javax.validation library for error handling.

    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compile group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'

Here we have a Cat class that has field id, name, breed, and date of birth.

package com.example.formsubmit

import org.springframework.format.annotation.DateTimeFormat

class Cat {
    private long id
    private String name
    private String breed
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date dateOfBirth

    long getId() { return id }
    void setId(long id) { this.id = id }
    String getName() { return name }
    void setName(String name) { this.name = name }
    String getBreed() { return breed }
    void setBreed(String breed) { this.breed = breed }
    Date getDateOfBirth() { return dateOfBirth }
    void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth }

This controller takes a get, and a post method for path “/”. We use thymeleaf for view here.

For error handling we need to @Valid, and BindingResult. We can use bindingResult to see which fields have errors, we do not show it here.

class HomeController {

    inputCat(Model model) {
        model.addAttribute("cat", new Cat())
        return "inputForm"

    showSubmittedCat(@Valid Cat cat, BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            model.addAttribute("errorMsg", "INPUT ERROR!")
            return "inputForm"
        return "submittedForm"

Form input UI:

<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
    <meta charset="UTF-8">
    <title>Form Input</title>
<p th:if="${errorMsg!=''}" th:text="${errorMsg}"></p>

<form action="/" th:action="@{/}" th:object="${cat}" method="post">
    <p>ID:<input type="text" th:field="*{id}"></p>
    <p>Name:<input type="text" th:field="*{name}"></p>
    <p>Breed:<input type="text" th:field="*{breed}"></p>
    <p>Date of birth:<input type="text" th:field="*{dateOfBirth}"></p>
    <button type="submit">Submit</button>


Display the submitted form:

<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
    <meta charset="UTF-8">
    <title>Submitted Form</title>
<p th:text="'ID: ' + ${cat.id}"/>
<p th:text="'Name:' + ${cat.name}"/>
<p th:text="'Breed:' + ${cat.breed}"/>
<p th:text="'Date of birth:' + ${#dates.format(cat.dateOfBirth, 'yyyy-MM-dd')}"/>
  • springboot/spring_form_input.txt
  • Last modified: 2020/05/26 11:25
  • by chongtin