掲示板でUserとCommentのリレーションを設定したので、Userごとのコメント一覧を表示してみましょう。
まず、どのユーザを対象にするかを指定しなければなりません。これにはformのパラメータを受け取る方法がつかえますが、ここではページ遷移のしやすさを考慮してURLの一部をパラメータとして利用する方法を使ってみましょう。例えばuser1というユーザ名のコメント一覧を表示するURLを「/bbs/user/user1」のようにします。
Controller
URLの一部をパラメータとして利用するには@PathVariableアノテーションを利用します。@RequestMappingで指定するURLの一部を{}で囲むようにすると、この部分が変数として扱えるようになります。
| 45 46 47 48 49 50 51 52 53 54 55 56 |     @RequestMapping("user/{username}")     public String user(ModelMap modelMap, @PathVariable("username") String username) {         try {             User user = userRepository.getOne(username);             List<Comment> commentList = user.getCommentList();             modelMap.addAttribute("username", username);             modelMap.addAttribute("commentList", commentList);             return "bbs/user";         } catch (EntityNotFoundException e) {             return "redirect:/bbs/";         }     } | 
- 45行目: URLのうちパラメータにしたい部分を{}で囲む。囲んだ文字列は@PathVariableの引数で参照できる。
- 46行目: URLから取得するパラメータを、メソッドの引数にし@PathVariableをつける。@PathVariableの引数はURLの{}の中の文字列にする。
- 49行目: UserとCommentでリレーションが設定されているので、UserのインスタンスからCommentのListが取得できる。
- 53-55行目: 48行目のgetOneでは、データが見つからない場合EntityNotFoundExceptionが発生するので、catchする。ここでは(手を抜いて)単に/bbs/にリダイレクトしている。
View
Userごとのコメントを表示するViewは次のようにします。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head>     <meta charset="UTF-8" />     <title>ユーザのコメント一覧</title> </head> <body> <h1>ユーザのコメント一覧</h1> <p><span th:text="${username}">username</span>のコメント一覧</p> <ol>     <li th:each="comment:${commentList}"><span th:text="${comment.text}">テキスト</span></li> </ol> </body> </html> | 

掲示板のトップページからユーザ名をクリックしてユーザごとのコメント一覧ページが見られるようにしてみましょう。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head>     <meta charset="UTF-8" />     <title>BBS</title> </head> <body> <h1>BBS</h1> <ol>     <li th:each="comment:${commentList}">         <a th:text="${comment.user.username}" th:href="@{/bbs/user/__${comment.user.username}__}">名前</a>:         <span th:text="${comment.text}">テキスト</span>     </li> </ol> <form th:action="@{/bbs/}" method="post">     <input type="text" name="text" /><input type="submit" /> </form> </body> </html> | 
- 11行目: もともとspanだったのをaに変更する。href属性はth:href属性で動的に設定することができる。@{}の中で変数を使うためには__${}__で囲む。
