Spring Boot/第五回 Spring Bootで Web (一覧表示)

Spring BootでWebの画面を作ってみる。
まずは顧客一覧画面から。

Contrller

ブラウザからのリクエストを受け取ってビジネスロジック呼んでブラウザにレスポンスを返すのがコントローラの役目。
コントローラは以下のようになる。

package tools.springsample.springsample05.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import tools.springsample.springsample05.domain.Customer;
import tools.springsample.springsample05.service.CustomerService;

@Controller    // a
@RequestMapping("customer")    // b
public class CustomerContrller {
    @Autowired
    private CustomerService customerService;

    @RequestMapping(method=RequestMethod.GET)    // c
    public String list(Model model) {    // d
        List<Customer> customers = customerService.findAll();
        model.addAttribute("customers", customers);    // e
        return "customer/list";    // f
    }
}

a -> コントローラであることを記すアノテーション
b -> コントローラがリクエストを受け取るURLを「customer」と定義する。
c -> URLの「customer」にGETメソッドが送られたときに実行するメソッドであることを記すアノテーション
d -> 画面に値を渡すModelを引数に受け取る。
e -> ビジネスロジックの顧客一覧取得結果をモデルにセットする。
f -> 画面のテンプレート「customer/list.html」を呼び出す。

@Controllerアノテーションでコントローラであることを宣言して、@RequestMapping("customer")アノテーションで受け取るURLを定義して、@RequestMapping(method=RequestMethod.GET)アノテーションでHTTPメソッドの何を受け取って処理するメソッドかを宣言すると、そのメソッド(今回だとCustomerContrllerクラスのlistメソッド)が呼ばれる。
リクエスト処理(listメソッド)内では処理結果をモデルにセットして結果を表示するURLを戻り値で返せば、後のテンプレートへ処理結果を引き継げる。
今回は処理結果として、CustomerServiceで提供している顧客リスト取得メソッド(findAllメソッド)の結果をModelに「customers」という名前でセットした。

テンプレート

動的なページの作成に「Thymeleaf」(タイムリーフ)というテンプレートエンジンを使用する。
HTMLに「th:xxx」や「data-th:xxx」などのタグを入れるとThymeleafが適切な値に置き換えてくれる。

HTMLのテンプレートは下記のフォルダに置く。

src/main/resources/template

コントローラで「customer/list」と返しているので、対象のテンプレートは下記のファイルとして記述する。

src/main/resources/template/customer/list.html

まず普通のHTMLとして表示する画面を下記のようにする。

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8"/>
  <title>顧客一覧</title>
  <style type="text/css">
    .list th {
      background-color: #cccccc;
      padding: 5px;
    }
    .list td {
      padding: 5px;
    }
  </style>
</head>
<body>
  <table class="list">
    <tr>
      <th>ID</th>
      <th>氏名</th>
      <th>アドレス</th>
    </tr>
    <tr>
      <td>xx</td>
      <td>name</td>
      <td>address</td>
    </tr>
  </table>
</body>
</html>

このHTMLをブラウザで開くと下記の通り。
f:id:nave_kazu:20150408010029j:plain

続いてHTMLにThymeleafで処理を書いて動的な結果を出力するように変える。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org/">    <!-- a -->
<head>
  <meta charset="UTF-8"/>
  <title>顧客一覧</title>
  <style type="text/css">
    .list th {
      background-color: #cccccc;
      padding: 5px;
    }
    .list td {
      padding: 5px;
    }
  </style>
</head>
<body>
  <table class="list">
    <tr>
      <th>ID</th>
      <th>氏名</th>
      <th>アドレス</th>
    </tr>
    <tr th:each="customer:${customers}">    <!-- b -->
      <td th:text="${customer.id}">xx</td>    <!-- c -->
      <td th:text="${customer.name}">name</td>    <!-- d -->
      <td th:text="${customer.email}">address</td>    <!-- e -->
    </tr>
  </table>
</body>
</html>

a -> Thymeleafの名前空間を宣言。
b -> コントローラでModelにセットしたリスト「customers」を取得して「th:each」で件数分ループさせる。
   ループ中の要素へアクセスするキーとして「customer」を指定する。
c -> 上で要素へのアクセスキー「customer」からIDを取得。
   customersはCustomerクラスのリストなので、Customerクラスのフィールドidのゲッターメソッド結果をTDタグの値として当てはめる。
d -> Customerクラスのフィールドnameのゲッターメソッド結果をTDタグの値として当てはめる。
e -> Customerクラスのフィールドemailのゲッターメソッド結果をTDタグの値として当てはめる。

Thymeleafの処理を追記したこのHTMLをブラウザで開くと下記の通り。
f:id:nave_kazu:20150408010113j:plain

追記前と変わらない。
つまりThymeleafの記述はブラウザには影響しない。
そのため、WebデザイナーとWebデベロッパーが分業して作業を進めることができる。
WebデザイナーがHTMLを書いて、そのあとWebデベロッパーがThymeleafの記述を追記する。
そのあとでもWebデザイナーはHTMLをブラウザで開いて表示内容を確認できるのでデザインを変更することもできる。

コンパイルして実行

以下のようにコンパイルする。

mvn package

続いて起動

mvn spring-boot:run

ブラウザで下記のアドレスにアクセスする。
http://localhost:8080/customer

するとデータベースの内容を読み込んで下記のように結果を表示する。
f:id:nave_kazu:20150408010152j:plain

まとめ

コントローラとテンプレートを作って動的な画面を表示してみた。
次回はフォームを使って更新系の画面を試してみる。

■ 参考文献 ■

この記事で参考にしたのは「はじめての Spring Boot」です。