こんにちは、くまごろーです。
今日は、リダイレクトについてまとめます。
1 何をしたいのか
こういうような、投稿詳細画面があったとします。
で、URLにリクエストパラメータとして投稿IDが付加されているとする。
http://localhost:8080/post/{postId}
投稿ID1番ならURLは「http://localhost:8080/post/1」、2番なら「http://localhost:8080/post/2」になる。
コメント投稿実行時に、同ページにリダイレクトさせたい場合、どうすればいいんだろうか?となったんですね。
<試してみたコード>
//コメント投稿処理 @PostMapping("/postComment") public String postComment(@Validated @ModelAttribute("comment") PostComment comment, BindingResult result, Authentication loginUser, UriComponentsBuilder builder) { /*コメント投稿処理*/ return "redirect:/post/{postId}?postComment" }
この方法だと、リダイレクトが無限ループしてしまうらしく、エラーになってしまいました。
2 解決策
UriComponentsBuilderというクラスでURLを組み立てることができるらしい。
@PostMapping("/postComment") public String postComment(@Validated @ModelAttribute("comment") PostComment comment, BindingResult result, Authentication loginUser, UriComponentsBuilder builder) { //リダイレクト先を指定 URI location = builder.path("/post/" + comment.getPostId()).build().toUri(); //コメント投稿処理 return "redirect:" + location.toString(); }
URIインスタンスでURLを組み立てたことで、投稿ID1番へのコメントなら「localhost:8080/post/1」へ、2番へのコメントなら「localhost:8080/post/2」へリダイレクトさせられるようになりました!
3 参考
Spring Bootでリダイレクト先のURLを組み立てる - Qiita