環境
Windows10 64bit
Spring Boot 2.6.2
Spring Tool Suite 4
JDK 11
thymeleaf 3
使用例
1.pom.xml 以下の内容を追加します
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
「pom.xml」を更新して、必要なライブラリがダウンロードされます。
操作方法
プロジェクトを右クリックして、「Maven(N)」->「プロジェクトの更新(U)」->「OK」をクリックします。
2.入力フォームファイル
ファイル名:src/main/resources/templates/user/index.html
書式
(1).formの定義
th:object="${フォーム名前}" コントローラの値とひも付きます。
(2).テキストボックスの定義 th:field="*{項目名}"
(3).入力チェックでエラーがある場合にメッセージが表示されます
th:if="${#fields.hasErrors('項目名’)}" th:errors="*{項目名}"
サンプルコード
<html xmlns:th="http://www.thymeleaf.org">
<form method="post" th:action="@{/user/confirm}" th:object="${userForm}">
<p>部署ID: <input type="text" th:field="*{userid}"/></p>
<div th:if="${#fields.hasErrors('userid')}" th:errors="*{userid}"></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="*{depart}"></p>
<div th:if="${#fields.hasErrors('depart')}" th:errors="*{depart}"></div>
<p><input type="submit" value="登録"></p>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>ユーザー登録</title>
</head>
<body >
<form method="post" th:action="@{/user/confirm}" th:object="${userForm}">
<p>部署ID: <input type="text" th:field="*{userid}"/></p>
<div th:if="${#fields.hasErrors('userid')}" th:errors="*{userid}"></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="*{depart}"></p>
<div th:if="${#fields.hasErrors('depart')}" th:errors="*{depart}"></div>
<p><input type="submit" value="登録"></p>
</form>
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>ユーザー登録</title>
</head>
<body >
<form method="post" th:action="@{/user/confirm}" th:object="${userForm}">
<p>部署ID: <input type="text" th:field="*{userid}"/></p>
<div th:if="${#fields.hasErrors('userid')}" th:errors="*{userid}"></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="*{depart}"></p>
<div th:if="${#fields.hasErrors('depart')}" th:errors="*{depart}"></div>
<p><input type="submit" value="登録"></p>
</form>
</body>
</html>
3.フォーム(Form)のクラスの定義(UserForm.java)
package com.example.demo;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
@Pattern(regexp = "^[0-9]+$", message = "数値を入力してください")
@Size(min = 6, max = 8, message = "6文字から8文字で入力してください")
@NotBlank(message = "項目入力必須")
package com.example.demo;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
public class UserForm {
@Pattern(regexp = "^[0-9]+$", message = "数値を入力してください")
private String userid;
@Size(min = 6, max = 8, message = "6文字から8文字で入力してください")
private String username;
@NotBlank(message = "項目入力必須")
private String depart;
//get setメソッド省略
}
package com.example.demo;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
public class UserForm {
@Pattern(regexp = "^[0-9]+$", message = "数値を入力してください")
private String userid;
@Size(min = 6, max = 8, message = "6文字から8文字で入力してください")
private String username;
@NotBlank(message = "項目入力必須")
private String depart;
//get setメソッド省略
}
アノテーションについて説明
(1).数値判定 @Pattern(regexp = “正規表現式", message = “メッセージ内容")
(2).空白判定 @NotBlank(message="メッセージ内容")
(3).文字数判定 @Size(min = 値1, max = 値2, message = “メッセージ内容")
4.コントローラのクラス(UserRegController.java)
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.validation.BindingResult;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
public class UserRegController {
public String top(Model model) {
if (!model.containsAttribute("userForm")) {
model.addAttribute("userForm", new UserForm());
public String confirm(@ModelAttribute("userForm") @Validated UserForm userForm, BindingResult result,
RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.userForm", result);
redirectAttributes.addFlashAttribute("userForm", userForm);
//redirect先にエラー文字列、入力文字列を渡します
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.validation.BindingResult;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/user")
public class UserRegController {
@GetMapping("/top")
public String top(Model model) {
if (!model.containsAttribute("userForm")) {
//初期画面表示 ビューでマッピング
model.addAttribute("userForm", new UserForm());
}
return "user/index";
}
//@Validateで入力チェックを行う
@PostMapping("/confirm")
public String confirm(@ModelAttribute("userForm") @Validated UserForm userForm, BindingResult result,
RedirectAttributes redirectAttributes) {
//入力チェックでエラーがある場合
if (result.hasErrors()) {
//エラー文字列を取得
redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.userForm", result);
redirectAttributes.addFlashAttribute("userForm", userForm);
//redirect先にエラー文字列、入力文字列を渡します
return "redirect:top";
}
return "user/result";
}
}
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.validation.BindingResult;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/user")
public class UserRegController {
@GetMapping("/top")
public String top(Model model) {
if (!model.containsAttribute("userForm")) {
//初期画面表示 ビューでマッピング
model.addAttribute("userForm", new UserForm());
}
return "user/index";
}
//@Validateで入力チェックを行う
@PostMapping("/confirm")
public String confirm(@ModelAttribute("userForm") @Validated UserForm userForm, BindingResult result,
RedirectAttributes redirectAttributes) {
//入力チェックでエラーがある場合
if (result.hasErrors()) {
//エラー文字列を取得
redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.userForm", result);
redirectAttributes.addFlashAttribute("userForm", userForm);
//redirect先にエラー文字列、入力文字列を渡します
return "redirect:top";
}
return "user/result";
}
}
5.入力値を受け取る側のファイル
ファイル名 src\main\resources\templates\user\result.html
<html xmlns:th="http://www.thymeleaf.org">
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>送信結果</title>
</head>
<body >
<div>ユーザー登録成功</div>
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>送信結果</title>
</head>
<body >
<div>ユーザー登録成功</div>
</body>
</html>
6.プログラム実行
プロジェクトを右クリックして、「実行(R)」->「Spring Boot アノテーション」をクリックします
動作確認
ブラウザ画面で「http://127.0.0.1:8080/topにアクセスします。
(1).「部署ID」、「ユーザー名」、「部署名」は入力しない、「登録」ボタンを押下します
「数値を入力してください」、「6文字から8文字で入力してください」、「項目入力必須」が表示されます。
(2).「部署ID」、「ユーザー名」、「部署名」は正しく入力すると、「http://127.0.0.1:8080/user/confirm」に遷移します
画面に「ユーザー登録成功」が表示されます。