Bookshelfアプリを作成する (Delete)

book.html テンプレートに削除確認画面へのリンクを追加する。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Book - 本を入れる本棚を指定する</title>
</head>
<body>

<h1>Book</h1>

<a href="/">トップ</a>


<table>
	<tr><td><img th:src="${book.image}" width="100" /></td></tr>
	<tr>
		<td th:text="${book.title}"></td>
		<td th:text="${book.author}"></td>
		<td><a th:href="@{'/book/edit/' + ${book.id}}" th:text="修正"></a></td>
		<td><a th:href="@{'/book/delete/' + ${book.id}}" th:text="削除"></a></td>
	</tr>
</table>

<hr />

<div>どの本棚に入れますか?</div>
<form action="/book" method="post">
	<input type="hidden" name="id" th:value="${book.id}" />
	<div>
		<select name="bookshelfId">
			<option value="0">本棚に入れない</option>
			<option th:each="bs : ${bookshelfList}" th:value="${bs.id}" th:selected="${bs.id == book.id}" th:text="${bs.name}"></option>
		</select>
	</div>
	<div><input id="submit" type="submit" value="本棚に入れる" /></div>
</form>


</body>
</html>

コントローラに削除確認画面に対応するURLマッピングを追加する。

	@RequestMapping(value = "/book/delete/{id}", method = RequestMethod.GET)
	public ModelAndView deleteConfirm(ModelAndView mav,
			@PathVariable long id) {
		mav.setViewName("deletebook");
		Optional<Book> data = repository.findById(id);
		mav.addObject("book", data.get());
		return mav;
	}

削除確認画面になる deletebook.html テンプレートを追加する。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Book - 本を削除する</title>
</head>
<body>

<h1>本の削除確認</h1>

<a href="/">トップ</a>


<table>
	<tr><td><img th:src="${book.image}" width="100" /></td></tr>
	<tr>
		<td th:text="${book.title}"></td>
		<td th:text="${book.author}"></td>
	</tr>
</table>
<form action="/book/delete" method="post">
	<input type="hidden" name="id" th:value="${book.id}" />
	<div><input id="submit" type="submit" value="削除する" /></div>
</form>


</body>
</html>

POSTメソッドで本の削除を実行する。

	@RequestMapping(value = "/book/delete", method = RequestMethod.POST)
	public ModelAndView delete(ModelAndView mav,
			@RequestParam("id") long id) {
		repository.deleteById(id);
		return new ModelAndView("redirect:/books");
	}