[Spring Boot2.4.2] フォームの値のバリデーション

pom.xml

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-validation</artifactId>
		</dependency>

src/main/resources/templates/test1/index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>submit</title>
</head>
<body >
<form method="post" action="#" th:action="@{/test1/testform}" th:object="${test1Form}">
<p><input type="text" id="id" name="id" th:field="*{id}"/></p>
<div th:if="${#fields.hasErrors('id')}" th:errors="*{id}"></div>

<p><input type="text" id="name" name="name" th:field="*{name}"></p>
<div th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></div>
<p><input type="submit" value="送信ボタン"></p>
</form>
</body>
</html>

MainController.java

package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Controller
@RequestMapping("/test1")
public class MainController {
	
    @GetMapping
    public String disp1(
    		Model model) {
    	model.addAttribute("test1Form", new Test1Form());
        return "test1/index";
    }
    @PostMapping("/testform")
	public String disp2(@Validated Test1Form test1Form
			,BindingResult br) {
		        if (br.hasErrors()) {
		        	return "test1/index";
		        }
			return "test1/testform";
		}
}

Test1Form.java

package com.example.demo;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Test1Form {
	@NotNull(message="必須項目です")
	private Integer id;
	
	@Size(min=3, max=6, message="3文字から6文字で入力して下さい")
	private String name;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

src/main/resources/templates/test1/testform.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>submit</title>
</head>
<body >

<p>OK</p>

</body>
</html>

やべええええええええええええ
SpringBoot面白いかも。