本のタイトルや画像を変更できるようにするには、まず変更するための画面に遷移できるようにする。
BookControllerに以下のメソッドを追加する。
@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
public ModelAndView edit(ModelAndView mav,
@PathVariable long id) {
mav.setViewName("edit");
Optional<Book> data = repository.findById(id);
mav.addObject("book", data.get());
return mav;
}
src/main/resources/templatesにedit.html を追加する。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>本の編集</title>
</head>
<body>
<h1>本の編集</h1>
<form action="/edit" method="post" th:object="${book}">
<input type="hidden" name="id" th:value="*{id}" />
タイトル: <input type="text" name="title" th:value="*{title}" />
<br />
著者: <input type="text" name="author" th:value="*{author}" />
<br />
画像URL: <input type="text" name="image" th:value="*{image}" />
<br />
<input type="submit" value="本を編集" />
<button onClick="history.back(); return false;">前のページにもどる</button>
</form>
</body>
</html>