SpringBootでCRUDを試してみた②~HTML(Thymeleaf)編~

前回は、CRUDに必要なJavaクラスを作成してきました。
今回は、Webブラウザーで表示させるためのHTMLを作成していきます。
※CSSの実装はありません
作成するhtmlファイルは下記3種類
1.index.html -Memberの一覧表示&それぞれに編集・削除ボタンを持たせる
2.edit.html -編集ボタンが押されると個のMemberを表示&編集可能な状態に
3.new.html -Memberの新規登録画面

htmlファイルは、resourcesフォルダ内のtemplates直下に入れていきます。

前回の記事はこちら↓

スポンサーリンク

index.html

html内でthymeleafテンプレートを使用する場合は、htmlダグ内に
xmlns:th=”http://www.thymeleaf.org
を追加するだけでOKです。JSPの<%@ taglib~~~よりも記述が複雑にならないので好きです。
また、JSPの<c:out value=~~よりも簡素的に書く事ができます。JSPはどうしても入れ子入れ子な記述になりがちでしたが、EL式で記述をしていくようなイメージで直感的に記述する事ができます。

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

	<table>
		<thead>
			<tr>
				<th>ID</th>
				<th>名前</th>
				<th>年齢</th>
				<th></th>
				<th></th>
			</tr>
		</thead>
		<tbody>
			<tr th:each="member : ${members}" th:object="${member}">
				<td th:text="*{id}"></td>
				<td th:text="*{name}"></td>
				<td th:text="*{age}"></td>
				<td><a th:href="@{/member/{id}/edit(id=*{id})}">編集</a></td>
				<td>
					<form th:action="@{/member/{id}(id=*{id})}" th:method="post">
						<input type="submit" value="削除" />
					</form>
				</td>
			</tr>
		</tbody>
	</table>
	<a href="/member/new">新規作成</a>
</body>
</html>

edit.html

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

	<h1>Editing Member</h1>
	<form th:action="@{/member/{id}/edit(id=*{id})}" th:method="post"
		th:object="${member}">
		<p>
			名前<input type="text" th:field="*{name}" />
		</p>
		<p>
			年齢<input type="text" th:field="*{age}" />
		</p>
		<p>
		<button type="submit">更新</button>
		</p>
	</form>
	<a href="/member">一覧画面へ</a>
</body>
</html>

new.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>New Member</h1>
	<form th:action="@{/member}" th:method="post">
		<p>
			名前<input type="text" name="name" />
		</p>
		<p>
			年齢<input type="text" name="age" />
		</p>
		<input type="submit" value="作成" />
	</form>

	<a href="/member">一覧画面へ</a>

</body>
</html>

完成~♪
Spring Bootの実行は、
1.プロジェクトを右クリック > 実行 > spring boot アプリケーション を選択
2.ブラウザーを立ち上げてlocalhost:8080~ を打ち込む
と表示がされます。
Spring Frameworkではtomcatサーバーから実行で自動的に立ち上がったのですが、bootでは自分でブラウザーを立ち上げるやり方でした。

タイトルとURLをコピーしました