yagibrary

あだ名のやぎと図書館のlibraryを組み合わせてyagibraryです。本から学んだことをみなさんに紹介します。

【読書メモ】【プロになるためのSpring入門】第11章 Spring MVC + Thymeleaf その3

その1、その2に関してはこちらの記事を見てください。
yagibrary.hatenablog.com
yagibrary.hatenablog.com

第11章 Spring MVC + Thymeleaf

11.13 Bean Validationを使用した入力チェック

入力チェックの仕組みとして、Java標準の仕組みであるBean Validationが便利です。Spring MVCは、Bean Validationとスムーズに連携することができます。ちなみに、Bean Validationの「Bean」と、Springの「Bean」は別物ですので、混同しないようにしましょう。

ユーザが入力する項目に対応したフィールドを定義し、Getter・Setterメソッドを作成します。入力項目の情報を保持する役割のクラスのことを、本書ではInputクラス、そのオブジェクトのことをInputオブジェクトと呼びます。

11.14 入力画面の表示方法

入力画面を表示するハンドラメソッドのソースコードソース11.27に示します。

▼ソース11.27 初期画面を表示するハンドラメソッド

@GetMapping("/reservation/display-form")
public String displayForm(@RequestParam String trainingId, Model model) {
    ReservationInput reservationInput = new ReservationInput(); ❶
    reservationInput.setTrainingId(trainingId); ❶
    reservationInput.setStudentTypeCode("EMPLOYEE"); ❶
    model.addAttribute("reservationInput", reservationInput); ❷
    List<StudentType> studentTypes = reservationService.findAllStudentType(); ❸
    model.addAttribute("studentTypeList", studentTypes); ❸
    return "reservation/reservationForm"; ❹
}

❶の行は、ReservationInputクラスのオブジェクトを用意しています。❷の行では、用意したInputオブジェクトをModelオブジェクトに格納しています。

❸の行は、受講生タイプのプルダウンメニューの選択肢のデータをServiceオブジェクトから取得し、Modelオブジェクトに格納しています。後述しますが、テンプレートファイルの中でプルダウンメニューを作成する際に参照します。

❹は、入力画面のビュー名を返しています。

11.15 入力画面のテンプレートファイル

▼ソース11.28 入力画面を表示するテンプレートファイル

<form th:action="@{/reservation/validate-input}" method="post" th:object="${reservationInput}"><table>
    <tr>
      <th>お名前</th>
      <td><input type="text" th:field="*{name}" /><div th:errors="*{name}"></div></td>
    </tr>
    <tr>
      <th>電話番号</th>
      <td><input type="text" th:field="*{phone}" /><div th:errors="*{phone}"></div>
      </td>
    </tr>
    <tr>
      <th>メールアドレス</th>
      <td><input type="text" th:field="*{emailAddress}" /><div th:errors="*{emailAddress}"></div>
      </td>
    </tr>
    ...

❶の行のth:action属性は、<form>タグのaction属性を出力する属性です。@{}の中に、入力データの送信先のパスを記述します。

❷の行は、入力項目の<input>タグに、th:field属性を指定しています。出力されるHTMLはソース11.29のようになります。

▼ソース11.29 入力項目の出力内容

<th>お名前</th>
<td><input type="text" id="name" name="name" value="">

入力画面を最初に表示したときは、Inputオブジェクトのnameプロパティはnullなので、出力されるvalue属性の値は空になっています。

ソース11.28の❸の行は、th:errors属性を指定し、nameプロパティを指定しています。

テンプレートファイルの続きをソース11.30に示します。

▼ソース11.30 入力画面を表示するテンプレートファイル(続き)

  ...
    <tr>
      <th>受講者のタイプ</th>
      <td>
        <select th:field="*{studentTypeCode}"><option
                    th:each="type : ${studentTypeList}"
                    th:value="${type.typeCode}"
                    th:text="${type.typeName}"
          />
        </select>
      </td>
    </tr>
  </table>
  <input type="hidden" th:field="*{trainingId}" />
  <input type="submit" value="予約内容を確認" />
</form>