7月27日

投稿者: | 2020年7月27日

MusicPlayerアプリケーションを作成する

新規プロジェクトを作成する。
「Spring スターター・プロジェクト」を選択する。
依存関係で以下の項目を選択して「完了」する。
・HyperSQL Database
・Spring Data JPA
・Spring Web
・Thymeleaf

プロジェクトができたら、pom.xml を開いて、以下の箇所を修正する。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

デスクトップの hsqldb.bat を編集してデータベースのインスタンスを追加する。

cd C:\se3java\hsqldb\lib
java -cp hsqldb.jar org.hsqldb.Server --database.0 db/mydata --dbname.0 mydata --database.1 db/musicplayer --dbname.1 musicplayer

application.properties ファイルを MyData プロジェクトからコピーする。
接続先データベースのインスタンス名の部分だけ修正する。

spring.datasource.url=jdbc:hsqldb:hsql://localhost/musicplayer
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.HSQLDialect
spring.jpa.hibernate.ddl-auto=update

IndexControllerを作成する。

package jp.abc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class IndexController {
    @RequestMapping("/")
    public ModelAndView index(ModelAndView mav) {
        mav.setViewName("layout");
        return mav;
    }
}

HTMLテンプレートを作成する。
まずはレイアウトのためのHTMLテンプレートを用意する。

layout.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>layout.html</title>
</head>
<body>

<section th:include="${template} :: ${fragment}">
<h1>layout</h1>
<p>本文です。</p>
</section>

</body>
</html>

musicplayer.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>MusicPlayer</title>
</head>
<body>

<div th:fragment="musicplayer">
<h1>MusicPlayer</h1>
<p>MusicPlayerフラグメント</p>
<p th:text="${msg}"></p>
</div>

</body>
</html>

コントローラにテンプレートとフラグメントの指定を追加する。

package jp.abc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class IndexController {
    @RequestMapping("/")
    public ModelAndView index(ModelAndView mav) {
        mav.addObject("template", "musicplayer");
        mav.addObject("fragment", "musicplayer");
        mav.setViewName("layout");
        return mav;
    }
}

Albumクラスを作成する。

package jp.abc;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Album {
	@Id
	@Column
	@GeneratedValue
	private long id;

	@Column(length = 100, nullable = false)
	private String title;

	@Column(length = 100, nullable = false)
	private String artist;

	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getArtist() {
		return artist;
	}
	public void setArtist(String artist) {
		this.artist = artist;
	}
}

IndexControllerの中でAlbumを作ってModelAndViewに渡す。

package jp.abc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class IndexController {
    @RequestMapping("/")
    public ModelAndView index(ModelAndView mav) {
    	Album album = new Album();
    	album.setTitle("STRAY SHEEP");
    	album.setArtist("米津玄師");
    	mav.addObject("album", album);
        mav.addObject("template", "musicplayer");
        mav.addObject("fragment", "musicplayer");
        mav.setViewName("layout");
        return mav;
    }
}

ModelAndViewに渡したalbumをテンプレートで表示する。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>MusicPlayer</title>
</head>
<body>

<div th:fragment="musicplayer">
<h1>MusicPlayer</h1>
<p>MusicPlayerフラグメント</p>
<p th:text="${msg}"></p>
<p th:text="${album.title}"></p>
<p th:text="${album.artist}"></p>
</div>

</body>
</html>

データベースと接続するためのRepositoryを作成する。

package jp.abc;

import org.springframework.data.jpa.repository.JpaRepository;

public interface AlbumRepository extends JpaRepository<Album, Long> {

}

コントローラからデータベースに保存する。

package jp.abc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class IndexController {
	@Autowired
	AlbumRepository repository;

    @RequestMapping("/")
    public ModelAndView index(ModelAndView mav) {
    	Album album = new Album();
    	album.setTitle("STRAY SHEEP");
    	album.setArtist("米津玄師");
    	repository.saveAndFlush(album);
    	mav.addObject("album", album);
        mav.addObject("template", "musicplayer");
        mav.addObject("fragment", "musicplayer");
        mav.setViewName("layout");
        return mav;
    }
}

コントローラを修正する。

package jp.abc;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class IndexController {
	@Autowired
	AlbumRepository repository;

    @RequestMapping("/")
    public ModelAndView index(ModelAndView mav) {
    	List<Album> list = repository.findAll();
    	mav.addObject("list", list);
        mav.addObject("template", "musicplayer");
        mav.addObject("fragment", "musicplayer");
        mav.setViewName("layout");
        return mav;
    }
}

IndexControllerが、テーブルの内容を読み込んでテンプレートに渡すように修正する。

package jp.abc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class IndexController {
	@Autowired
	AlbumRepository repository;

    @RequestMapping("/")
    public ModelAndView index(ModelAndView mav) {
    	Album album = new Album();
    	album.setTitle("STRAY SHEEP");
    	album.setArtist("米津玄師");
    	repository.saveAndFlush(album);
    	mav.addObject("album", album);
        mav.addObject("template", "musicplayer");
        mav.addObject("fragment", "musicplayer");
        mav.setViewName("layout");
        return mav;
    }
}

テンプレート内で、listの内容をループで表示するように修正する。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>MusicPlayer</title>
</head>
<body>

<div th:fragment="musicplayer">
<h1>MusicPlayer</h1>
<p>MusicPlayerフラグメント</p>
<p th:text="${msg}"></p>

<table>
  <tr><th>ID</th><th>タイトル</th><th>アーティスト</th></tr>
  <tr th:each="album : ${list}">
    <td th:text="${album.id}"></td>
    <td th:text="${album.title}"></td>
    <td th:text="${album.artist}"></td>
  </tr>
</table>

</div>

</body>
</html>