LoginSignup
16

More than 3 years have passed since last update.

SpringでFlash Scopeを使ってリダイレクト先画面にパラメーターを渡す

Posted at

画面遷移のあるアプリケーションでリダイレクトする場合、リダイレクト先にパラメータを渡したいケースがあります。
実現方法はいくつかありますが、ここではSpring + Flash Scopeを使ったやり方を紹介します。

Flash Scopeとは

1回のリダイレクトで有効なスコープです。
Request Scopeより長くSession Scopeより短いといったイメージになります。

実現方法

RedirectController.java
@Controller
public class RedirectController {

    // リダイレクト元エンドポイント
    @GetMapping("view1")
    public String view1(RedirectAttributes redirectAttributes) {
        redirectAttributes.addFlashAttribute("key1", "value1");
        return "redirect:/view2";
    }

    // リダイレクト先画面
    @GetMapping("view2")
    public ModelAndView view2(Model model, ModelAndView modelAndView) {
        // Flash Scopeから値の取り出し
        String value1 = (String) model.getAttribute("key1");
        modelAndView.addObject("redirectParameter", value1);
        modelAndView.setViewName("demo/redirect/view2");
        return modelAndView;
    }
}

リダイレクト元のエンドポイントでRedirectAttributes#addFlashAttributeを利用して、リダイレクト先に渡したいパラメータを指定します。リダイレクト先の画面ではそれをModel#getAttributeを利用して取り出します。

よくあるやり方としては、Sessionに値を格納してリダイレクト先で取得、という方法ですが、ほとんどのケースでSessionから値を取りだしたらその値を明示的にremoveする必要があります(メモリリークの温床となるため)。
Flash Scopeを使うことで、一度リダイレクト先に遷移したら以降はリダイレクト先画面をF5リロードしても利用することができなくなります(remove等の考慮は不要です)。

以上です。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16