3
9

More than 3 years have passed since last update.

Spring Boot セッション属性(@SessionAttributes)の使い方

Posted at

Spring Bootのセッションのやり方です。

Formクラス

LoginForm.java
public class LoginForm implements Serializable {

    @NotEmpty(message = "Enter Id")
    private String id;

    @NotEmpty(message = "Enter Password")
    private String password;

    private String check;
    private String radio;
    private String select;
//getter,setter省略

Controllerクラス

IndexController.java
@Controller
@RequestMapping("/index")
//@SessionAttributesは1つのController内で扱う複数のリクエスト間で
//データを共有する場合に有効。
//types属性にHTTPセッションに格納するオブジェクトクラスを指定する。
@SessionAttributes(types=LoginForm.class)
public class IndexController {

    /*
     * オブジェクトをHTTPセッションに追加する
     */
    @ModelAttribute("loginForm")
    public LoginForm setUpLoginForm(){
        return new LoginForm();
    }

    //Modelから取得するオブジェクトの属性名は、@ModelAttributeのvalue属性に指定する。
    //今回だと、LoginFormクラスのselectを指定している。
    @PostMapping("check")
    public String loginCheck(@ModelAttribute("loginForm") @Validated LoginForm loginForm, BindingResult res,
            @ModelAttribute("select") String select, Model model) {
        //入力チェック
        if (res.hasErrors()) {
            return "login";
        }
    }

    //今回だと、LoginFormクラスのidを指定している。
    @GetMapping("form")
    public String create(Model model, @ModelAttribute("id") String id) {
        return "create";
    }

}

Viewからアクセスする実装例

<h3 th:text=${loginForm.id}></h3>
<h3 th:text=${loginForm.select}></h3>
3
9
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
3
9