JavaScriptで動きをつけてみる

本の編集画面で画像URLを入力したときに、画像のプレビューを表示する。

src/main/resources にある static フォルダに js フォルダを新規作成する。
そのフォルダに、jQueryファイルを貼り付ける。

まず、開発者ツールのJavaScriptコンソールでやりたい動きを確認する。
うまく動いたら、その内容を script タグ内に記述する。

imgタグに表紙という意味でid=coverを割り当てておく。

editbook.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Book - 本の編集</title>
<script src="/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function() {
	$('[name=image]').on('keyup', function() {
		$('#cover').prop('src', $(this).val());
	})
});
</script>
</head>
<body>

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

<h1>本の編集</h1>

<img id="cover" th:src="${book.image}" width="200" />

<form action="/book/edit" method="post">
	<input type="hidden" name="id" th:value="${book.id}" />
	<div>タイトル: <input type="text" name="title" th:value="${book.title}" /></div>
	<div>著者: <input type="text" name="author" th:value="${book.author}" /></div>
	<div>画像URL: <input type="text" name="image" th:value="${book.image}" /></div>
	<div><input id="submit" type="submit" value="修正" /></div>
</form>


</body>
</html>

本のリストの画面も同じような動きになるように修正してみる。

books.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Book - 本のリスト</title>
<script src="/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function() {
	$('[name=image]').on('keyup', function() {
		$('#cover').prop('src', $(this).val());
	})
});
</script>
</head>
<body>

<h1>Book list</h1>

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

<table>
	<tr>
		<th>ID</th><th>画像</th><th>タイトル</th><th>著者</th><th>本棚</th>
	</tr>
	<tr th:each="book : ${list}">
		<td th:text="${book.id}"></td>
		<td><img th:src="${book.image}" height="50" /></td>
		<td><a th:href="@{'/book/' + ${book.id}}" th:text="${book.title}"></a></td>
		<td th:text="${book.author}"></td>
		<td th:if="${book.bookshelf != null}" th:text="${book.bookshelf.name}"></td>
		<td th:if="${book.bookshelf == null}" th:text="本棚に入れてません"></td>
	</tr>
</table>

<hr />

<div>新しい本</div>
<img id="cover" src="" width="200" />
<form action="/addbook" method="post">
	<div>タイトル: <input type="text" name="title" /></div>
	<div>著者: <input type="text" name="author" /></div>
	<div>画像URL: <input type="text" name="image" /></div>
	<div><input id="submit" type="submit" value="+追加" /></div>
</form>


</body>
</html>

今のままでは、画像URLを入力しても保存していないので、サーバー側に画像URLを保存する処理を追加する。

	@RequestMapping(value="/addbook", method=RequestMethod.POST)
	public ModelAndView formPost(ModelAndView mav,
			@RequestParam("title") String title,
			@RequestParam("author") String author,
			@RequestParam("image") String image) {
		Book book = new Book();
		book.setTitle(title);
		book.setAuthor(author);
		book.setImage(image);
		repository.saveAndFlush(book);
		return new ModelAndView("redirect:/books");
	}