SpringBoot フォームで入力チェックするサンプル
環境
SpringBoot 3
JavaSE 17
1.pom.xmlの定義
必要なライブラリです。spring-boot-starter-validationは、
入力チェックで使用します。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2.値を送信する側のファイル(index.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<title>submit</title>
</head>
<body>
<form method="post" th:action="@{/test1/inputCheck}" th:object="${testForm}">
<p> 番号:<input type="text" th:field="*{id}" /></p>
<div th:if="${#fields.hasErrors('id')}" th:errors="*{id}"></div>
<p>ユーザー名:<input type="text" th:field="*{username}" /></p>
<div th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></div>
<p>住所:<input type="text" th:field="*{addr}" /></p>
<div th:if="${#fields.hasErrors('addr')}" th:errors="*{addr}"></div>
<p><input type="submit" value="送信" /></p>
</form>
</body>
</html>
3.コントローラのクラス(MainController.java)
コントローラで受信し@Validatedで入力チェックの対象になります。
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.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/test1")
public class MainController {
@GetMapping("/login")
public String login(Model model) {
if(!model.containsAttribute("testForm")) {
model.addAttribute("testForm", new TestForm());
}
return "test1/index";
}
@PostMapping("/inputCheck")
public String inputCheck(@ModelAttribute("testForm") @Validated TestForm testForm,
BindingResult brt,
RedirectAttributes redirectAttributes) {
if(brt.hasErrors()) {
redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.testForm", brt);
redirectAttributes.addFlashAttribute("testForm", testForm);
return "redirect:login";
}
return "test1/testform";
}
}
説明
画面の値がTestFormにセットされ、@Validatedで入力チェックが行われます。
以下のようにも書けます。
@ModelAttribute @Validated TestForm testForm
4.フォームのクラス(TestForm.java)
項目に追加した@NotNullアノテーション等で入力チェックします。
package com.example.demo;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
public class TestForm {
@Pattern(regexp = "^[0-9]+$", message = "数値を入力してください")
private String id;
@Size(min = 4, max = 8, message = "4文字から8文字で入力してください")
private String username;
@NotBlank(message = "必須項目です")
@Size(max = 8, message = "最大8文字までです")
private String addr;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
}
説明
null 空文字("") 半角スペース
NotNull エラーになる ok ok
NotEmpty エラーになる エラーになる ok
NotBlank エラーになる エラーになる エラーになる
5.値を受け取る側のファイル(testform.html)
th:object=のtestFormは、コントローラの値とひも付きます。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<title>submit</title>
</head>
<body>
<p>test ok</p>
</body>
</html>
6.実行して確認する
http://localhost:8765/test1/login