0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Spring Boot 開発備忘録 基本構成・画面表示編

0
Posted at

はじめに

Spring Bootを学習したので、下記の事を何時でも確認しやすい用に備忘録としてまとめます。

  • Controllerはどのように作成するのか
  • URLとメソッドはどう紐付けるのか
  • ControllerからHTMLへ値を渡すにはどうするのか
  • Serviceはどのように呼び出すのか

この記事では、Spring Bootの基本構成と、HTMLを表示するまでの流れを備忘録としてまとめます。

特定のアプリに依存しないように、Sampleという汎用的な名前を使用します。

コードの見分け方

この記事では、自分で作成するものと、Springなどが用意しているものをコード内のコメントで区別します。

@Controller // Springが用意
public class SampleController { // 自分で作成

    private String sampleName; // 自分で作成
}

主な区別は次のとおりです。

  • 自分で作成:クラス名、変数名、メソッド名、URLなど
  • Springが用意:アノテーション、クラス、メソッドなど
  • Javaが用意StringListOptionalなど
  • Jakartaが用意:JPAや入力チェックで使うアノテーションなど

Spring Bootの基本的な処理の流れ

画面からデータベースまで処理する場合、基本的には次のような流れになります。

ブラウザ
  ↓
Controller
  ↓
Service
  ↓
Repository
  ↓
データベース

それぞれの役割は次のとおりです。

Controller

ブラウザからのアクセスを受け取ります。
主に次の処理を担当します。

  • HTMLを表示する
  • 画面から送信された値を受け取る
  • Serviceのメソッドを呼び出す

Service

アプリケーションの処理を担当します。
主に次の処理を記載します。

  • 計算
  • データの加工
  • 外部APIの呼び出し
  • Repositoryの呼び出し

Repository

データベース操作を担当します。

  • 登録
  • 取得
  • 更新
  • 削除

Entity

データベースのテーブルをJavaクラスで表します。

Form

画面から入力された値を受け取ります。

DTO

複数のデータをまとめて受け渡すためのクラスです。

Controllerを作成する

Controllerは、ブラウザからのアクセスを受け取るクラスです。

package com.example.sample.controller; // 自分で作成

import org.springframework.stereotype.Controller;

@Controller // Springが用意
public class SampleController { // 自分で作成

}

@Controllerを付けることで、このクラスが画面表示用のControllerであることをSpringへ伝えます。

次のクラス名は自分で決めます。

SampleController

一般的には、機能名の後ろにControllerを付けます。

ItemController
UserController
ProductController

GETリクエストでHTMLを表示する

指定したURLへアクセスされたときに、HTMLを表示する基本形です。

package com.example.sample.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class SampleController {

    @GetMapping("/sample") // Springが用意。URLは自分で決める
    public String showSamplePage() { // 自分で作成

        return "sample-page"; // HTML名は自分で決める
    }
}

ブラウザから次のURLへアクセスします。

http://localhost:8080/sample

すると、次のHTMLが表示されます。

src/main/resources/templates/sample-page.html

このコードで自分が決めている部分は次のとおりです。

"/sample"
showSamplePage
"sample-page"

returnには、HTMLの拡張子である.htmlを付けません。

return "sample-page";

ControllerからHTMLへ値を渡す

Java側で作成した値をHTMLへ渡す場合は、Springが用意しているModelを使用します。

Controller

package com.example.sample.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class SampleController {

    @GetMapping("/sample")
    public String showSamplePage(Model model) { // ModelはSpringが用意

        String sampleMessage = "サンプルです";
        // 変数名と値は自分で作成

        model.addAttribute(
                "message", // HTMLで使用する名前
                sampleMessage
        );

        return "sample-page";
    }
}

model.addAttribute()を使って、HTMLへ値を渡します。

model.addAttribute("message", sampleMessage);

第1引数は、HTMLから値を参照するときの名前です。

第2引数は、実際にHTMLへ渡す値です。

HTML

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>サンプル画面</title>
</head>
<body>

    <p th:text="${message}"></p>

</body>
</html>

Controllerで指定した名前と、HTMLの${}内の名前を一致させます。
Controller側です。

model.addAttribute("message", sampleMessage);

HTML側です。

<p th:text="${message}"></p>

messageの名前が異なると、値を表示できません。

Serviceを作成する

Controllerにすべての処理を書くのではなく、アプリケーションの処理をServiceへ分けます。

package com.example.sample.service;

import org.springframework.stereotype.Service;

@Service // Springが用意
public class SampleService { // 自分で作成

    public String createMessage(String sampleName) {
        // メソッド名と引数名は自分で作成

        return "こんにちは、" + sampleName + "さん";
    }
}

@Serviceを付けることで、このクラスをSpringが管理するServiceとして登録します。

自分で決める部分は次のとおりです。

SampleService
createMessage
sampleName

ControllerからServiceを呼び出す

ControllerからServiceを使用するときは、コンストラクタでServiceを受け取ります。

package com.example.sample.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.example.sample.service.SampleService;

@Controller
public class SampleController {

    private final SampleService sampleService;

    public SampleController(
            SampleService sampleService) {

        this.sampleService = sampleService;
    }

    @GetMapping("/sample")
    public String showSamplePage(Model model) {

        String message =
                sampleService.createMessage("サンプル");

        model.addAttribute("message", message);

        return "sample-page";
    }
}

処理の流れは次のとおりです。

Controller
  ↓
Serviceのメソッドを呼び出す
  ↓
Serviceが処理結果を返す
  ↓
ControllerからHTMLへ渡す

SpringがSampleServiceのインスタンスを作成し、Controllerへ渡す仕組みをDI(依存性注入)と呼びます。

HTML表示とリダイレクトの違い

HTMLを表示するときは、HTML名を返します。

return "sample-page";

次のHTMLが表示されます。

src/main/resources/templates/sample-page.html

別のURLへ移動するときは、redirect:を付けます。

return "redirect:/samples";

これはHTMLを直接表示する処理ではありません。

ブラウザから/samplesへ再度アクセスさせます。

@Controller@RestControllerの違い

@Controller

主にHTMLを表示するときに使用します。

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class SamplePageController {

    @GetMapping("/sample")
    public String showPage() {

        return "sample-page";
    }
}

returnした文字列は、HTML名として扱われます。

@RestController

文字列やJSONをレスポンスとして直接返すときに使用します。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SampleApiController {

    @GetMapping("/api/sample")
    public String getSample() {

        return "サンプルデータ";
    }
}

この場合、ブラウザには次の文字列が直接表示されます。

サンプルデータ

違いを簡単にまとめると、次のようになります。

@Controller
  → HTMLを表示する

@RestController
  → 文字列やJSONを返す

まとめ

今回使用したクラスの役割は次のとおりです。

Controller
  → URLの受付とHTMLの表示

Service
  → アプリケーションの処理

Model
  → ControllerからHTMLへ値を渡す

画面を表示するときの基本形は次のとおりです。

ブラウザ
  ↓
Controller
  ↓
Service
  ↓
Controller
  ↓
Model
  ↓
HTML

次の記事では、Formを使った入力値の受け取りと、バリデーションについてまとめます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?