LoginSignup
90
81

More than 5 years have passed since last update.

SpringMVCでリダイレクト先ページにパラメータを渡す方法

Last updated at Posted at 2012-09-11

コントローラのハンドラからハンドラにリダイレクトする際、パラメータを渡してリダイレクト先のJSP等に表示する方法。

Modelを使う

以下コントローラのサンプル。

//ここにアクセスすると...
@RequestMapping(value = "/from", method = RequestMethod.GET)
public String from(Model model) {
    //メッセージhogehogeを渡す
    model.addAttribute("message", "hogehoge");
    return "redirect:/to";
}

//こっちにリダイレクトする
@RequestMapping(value = "/to", method = RequestMethod.GET)
public String to(@Param(value = "message") String message, Model model) {
    // 受け取ったmessageをJSPなどに表示する
    model.addAttribute("message", message);
    return "view_massage";
}   
view_message.jsp
<!-- /to ハンドラが表示するJSP -->
<body>
    <!--hogehogeが表示される-->
    Message=${message}
</body>

Model#addAttributeでセットした値は、[URL]/to?message=hogehoge といったように、リダイレクト先URLのGETパラメータに入ってしまうのでちょっときもち悪い。もし日本語などを渡したいときはURLEncodeも意識しないといけないので面倒。

RedirectAttributesを使う

Spring3.1以降ではRedirectAttributesを使ってよりシンプルに書くことができる。

//ここにアクセスすると...
@RequestMapping(value = "/from", method = RequestMethod.GET)
public String from(RedirectAttributes attributes) {
    //メッセージhogehogeを渡す
    attributes.addFlashAttribute("message","hogehoge");
    return "redirect:/to";
}

//こっちにリダイレクトする
@RequestMapping(value = "/to", method = RequestMethod.GET)
public String to() {
    return "view_massage";
}   

3.1ではFlash Scopeというものが導入されていて、RedirectAttributesではそこにデータを格納してリダイレクトするかたち。日本語もencode/decode無しに送れるし、リダイレクト先コントローラでModelに値をセットする作業もいらなくて楽。

※Bean設定に <mvc:annotation-diven /> を書かないとこの機能が有効化されないので注意

90
81
0

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
90
81