LoginSignup
3
0

More than 1 year has passed since last update.

はじめに

株式会社ピーアールオー(あったらいいな!を作ります) Advent Calendar 2022 の7日目になります。
前日は[AWS]SAMでTypeScriptがサポートされたので5分でAPIを作成するでした。

前にSpring Boot + RemoteContainerの環境構築をしてHelloWorldまで表示させたので、SpringMVCの機能を利用して簡単なWebアプリケーションを作ります。

build.gradle

build.gradleファイルのdependenciesにThymeleafなど定義します。
spring initializrで設定するでも問題ない。

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	developmentOnly 'org.springframework.boot:spring-boot-devtools'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'
}
spring boot Dependencies 説明
Thymeleaf テンプレートエンジン
Spring Web web表示に必要
Spring Boot DevTools javaのソースコードが変更された際にspring boot を自動で再起動するための機能
lombok コンストラクタ、ゲッター、セッターを自動で作るライブラリ

トップページの表示

templates下にindex.htmlを作成
htmlタグに、Thymeleaf用スキーマ定義しておく。

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>トップページ</title>
</head>
<body>
    <h1>Advent Calendar 2022</h1>
    <ul>
        <li>
            <!-- "@{/issues}" @ はthymeleafでリンクを表す記法 -->
            <!-- springboot 起動せずともhtmlを確認出来る。タイムリーフ挟まないナチュラルテンプレート -->
            <a href="./articles/article_list.html" th:href="@{/articles}">記事一覧</a>
        </li>
    </ul>
</body>
</html>

IndexControllerを作成する。

package com.example.its.web;

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

@Controller
public class IndexController {
  
  // GET /
  @GetMapping("/")
  public String index() {
    // 前のパスの拡張子はSpringMVCが補完してくれるので書かなくてよい
    return "index";
  }

}

http://localhost:8080/ にアクセス
image.png

MVCの機能を使う

トップページのhtmlに記事一覧ページに遷移するリンクを書いたので遷移先のページを作る。

Entity

package com.example.its.domain.articles;

import lombok.AllArgsConstructor;
import lombok.Data;

//クラスの全てのフィールドを引数にとる。
@AllArgsConstructor
@Data
public class ArticleEntity {
  private long id;
  private String title;
  private String impressions;
}

Service

package com.example.its.domain.articles;

import java.util.List;
import org.springframework.stereotype.Service;

@Service
public class ArticleService {
  
  public List<ArticleEntity> findAll(){
    return List.of(
      new ArticleEntity(1,"Angular フォームボタンの無効について","very good"),
      new ArticleEntity(2,"Wingetで簡単!開発PCセットアップ(Windows)","very good"),
      new ArticleEntity(3,"DirectMLで試す、非NVIDIA系GPUで機械学習","very good"),
      new ArticleEntity(4,"Wingetで簡単!開発PCセットアップ(Windows)","very good"),
      new ArticleEntity(5,"DirectMLでStable Diffusionを動かしてみる","very good"),
      new ArticleEntity(6,"Googleカレンダーの当日予定をSlackに通知する","very good"),
      new ArticleEntity(7,"[AWS]SAMでTypeScriptがサポートされたので5分でAPIを作成する","very good")
    );
  }
}

Controller

package com.example.its.web.article;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.example.its.domain.articles.ArticleService;
import lombok.RequiredArgsConstructor;

@Controller
@RequiredArgsConstructor

public class ArticleController {
  // GET /issue
  
  private final ArticleService articleService;
  /**
   * 
   * @param model
   * @return 
   */
  @GetMapping("/articles")
  public String showList(Model model){
    model.addAttribute("articleList", articleService.findAll());
    return "articles/article_list";
  }
}

テンプレート

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>記事一覧</title>
</head>
<body>
    <h1>記事一覧</h1>
    <a href="../index.html" th:href="@{/}">トップページ</a>
    <table>
        <thead>
            <tr>
                <th scope="col">タイトル</th>
                <th scope="col">感想</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="article : ${articleList}">
                <th scope="col" th:text="${article.title}">(title)</th>
                <td th:text="${article.impressions}">(impression)</td>
            </tr>
        </tbody>
    </table>
</body>
</html>

http://localhost:8080/articles に以下のようなページが出来ました。
image.png

終わりに

SpringBootを利用して簡単なWEBアプリケーションを作成することが出来ました。
知らない機能もまだまだ沢山ありそうなのでまた遊んでみます。

vscodeでやってるが、IntelliJで触った方がいいのだろうか。。
兎にも角にもこないだ作った環境が動くことを確認出来て満足です。

参考

Spring Boot + Spring MVC ~サンプルアプリ実装~
【SpringBoot】Webアプリケーション作成
【Java】Thymeleaf基本 (SpringBoot)

3
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
3
0