かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

Spring BootでSessionを扱う(SessionAttribute版)

SessionAttributeを使うと同じコントローラ内でオブジェクトを持ちまわることが出来ます。

詳細は全部こっちに書いてあります。 5.8. セッション管理 — TERASOLUNA Server Framework for Java (5.x) Development Guideline 5.0.0.RELEASE documentation

試してみたことメモ

Sessionを使うためにControllerにSessionAttirbutesアノテーションをつけてvalueにオブジェクトの名前をつけます。そして、同じ名前のModelAttributeをつけたファクトリメソッドをInputControllerに作ります。

こんな感じで。

@Controller
@RequestMapping("/input")
@SessionAttributes(value = "inputForm")
public class InputController {

    @ModelAttribute("inputForm")
    InputForm inputForm() {
        System.out.println("create inputForm");
        return new InputForm();
    }
}

これを受け取るコントローラのメソッドがあると、自動的にオブジェクトが生成されてセッションに格納されます。

// これが呼ばれる前にinputForm()メソッドが呼ばれる
@RequestMapping(value = "/input1", method = RequestMethod.GET)
public String input1(InputForm form) {
    return "input/input1";
}

必要なくなったらSessionStatesのsetCompleteで破棄できます。

@RequestMapping(value = "/complete", method = RequestMethod.POST)
public String complete(
        @Validated(value = {InputForm.Input1.class, InputForm.Input2.class, InputForm.Input3.class}) InputForm form, 
        BindingResult result,
        SessionStatus sessionStatus,
        RedirectAttributes redirectAttributes) {
    if (result.hasErrors()) {
        return "input/input3";
    }

    // いらなくなったので破棄
    sessionStatus.setComplete();
    redirectAttributes.addFlashAttribute("inputForm", form);
    return "redirect:/greet";
}

Thymeleafのテンプレートからは${inputForm}という感じでアクセスできます。割と便利ですね。