プログラミング逆引き辞典

~ 多言語対応のプログラミングレシピ ~

SpringBoot入門 vol.11:データバインドで画面とフィールドをマッピングしよう

データバインドで画面の入力項目とオブジェクトのフィールドをマッピングを行う
これにより画面での入力時にバリデーションチェックを実施する
 
 

①CustomerFormクラスに「Bean Validation」を設定

package com.example.web;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

import lombok.Data;

@Data
public class CustomerForm {
    private Integer id;
    //ポイント1
    @NotBlank
    @Size(min = 1, max = 20)
    private String name;
    @Size(max = 100)
    private String email;
}

 

【ポイント】

1-1.@NotBlank
「Null」、「空文字」、「半角スペース」をチェックするバリデーション
 

■アノテーションと許容可否

アノテーション Null 空文字 半角スペース 全角スペース
NotBlank NG NG NG OK
NotEmpty NG NG OK OK
NotNull NG OK OK OK

※その他のBeanバリデーションはこちら
Beanバリデーション一覧
 
 
1-2.@Size(min = 最小値, max = 最大値)
文字の長さをチェックするバリデーション
 
 


②コントローラークラス(CustomerController.java)に「@Validated」を付与

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 com.example.domain.Customer;
import com.example.service.CustomerService;

@Controller
public class CustomerController {
            .
            .
            .

    @PostMapping("create")
    //ポイント1
    String regist(@ModelAttribute @Validated CustomerForm customerForm, BindingResult result, Model model) {
        //ポイント2
        if (result.hasErrors()) {
            return create(customerForm);
        }

        Customer customer = new Customer();
        BeanUtils.copyProperties(customerForm, customer);

        customerService.insert(customer);

        return "redirect:/";
    }
}

 

【ポイント】

1.@Validated
「@Validated」を付与して、CustomerFormクラスに設定したバリデーションチェックを行う
更にBindingResult型の変数「result」にバリデーションチェックの結果が格納される
 
2.result.hasErrors()
バリデーションチェックでエラーがあった場合はcreate()メソッドを呼び出し、顧客登録画面を表示
 
 


③顧客登録画面(crate.html)を編集してバリデーションチェック時のエラーメッセージ表示

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>顧客登録</title>
</head>
<body>
    <h1>顧客登録</h1>
    <form th:action="@{/create}" th:object="${customerForm}" method="post">
        <table>
            <tr>
                <th>名前</th>
                <!-- ポイント1 -->
                <td><input type="text" name="name" th:field="*{name}"><span th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></span></td>
            </tr>
            <tr>
                <th>メールアドレス</th>
                <td><input type="text" name="email" th:field="*{email}"><span th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></span></td>
            </tr>
        </table>
        <input type="submit" value="登録">
    </form>
</body>
</html>

 

【ポイント】

1-1.th:if="${#fields.hasErrors(‘フィールド名’)}"
対象のフィールドのデータバインドエラー時
 
1-2.th:errors="*{‘フィールド名’}"
対象のフィールドに関するエラーメッセージをタグ内の文字列に置換

【エラーメッセージを確認】

顧客登録画面で下記内容を入力して登録ボタンを押下
・名前:空欄
・メールアドレス:101文字以上
 

 

 
エラーメッセージが表示されることを確認
 
 


前へ次へ
 
目次へ戻る