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

pom.xml

1
2
3
4
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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

1
2
3
4
5
6
7
8
9
10
11
12
<!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面白いかも。