springboot:spring_form_input

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.

@Controller
class HomeController {

    @GetMapping("/")
    inputCat(Model model) {
        model.addAttribute("cat", new Cat())
        return "inputForm"
    }

    @PostMapping("/")
    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">
<head>
    <meta charset="UTF-8">
    <title>Form Input</title>
</head>
<body>
<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>
</form>

</body>
</html>

Display the submitted form:

<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Submitted Form</title>
</head>
<body>
<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')}"/>
</body>
</html>
  • springboot/spring_form_input.txt
  • Last modified: 2020/05/26 11:25
  • by chongtin