简体   繁体   English

做“model.addAttribute()”和“session.setAttribute()”的区别

[英]difference in doing “model.addAttribute()” and “session.setAttribute()”

Can someone give me a clear difference in using "model.addAttribute()" and "session.setAttribute()"?有人可以告诉我使用“model.addAttribute()”和“session.setAttribute()”的明显区别吗?

''' '''

@PostMapping("/auth")
    public String loginPost(@RequestParam String username,@RequestParam String password,Model model,HttpSession session) {
        SignupDTO signupDTO = signupService.authUser(username, password);
        if (signupDTO != null) {

            model.addAttribute("email", signupDTO.getEmail());
            model.addAttribute("name", signupDTO.getName());
            model.addAttribute("salutation", signupDTO.getSalutation());



            session.setAttribute("role", signupDTO.getRole());
            session.setAttribute("name", signupDTO.getName());
            session.setAttribute("email", signupDTO.getEmail());
            session.setAttribute("salutation", signupDTO.getSalutation());
            return "success";
        } else {
            model.addAttribute("message", "Sorry username and password are not correct!");
            return "login";
        }
    }

''' '''

The main difference is that model is per request while the session is per Http Session.主要区别在于 model 是每个请求,而 session 是每个 Http Z71C7AE294B3ABD866B43FB9E。 That means every request will have a new model.这意味着每个请求都会有一个新的 model。 A model will be destroyed after processing an request and a brand new model will be created for the next request. model 将在处理请求后销毁,并为下一个请求创建一个全新的 model。

So if you want the subsequent requests can access the value that you set in the previous requests in the same session, you have to add it to the session but not the model.因此,如果您希望后续请求可以访问您在相同 session 中的先前请求中设置的值,则必须将其添加到 session 而不是 Z20F35E630DAF44DBFA4C3F68F5399D。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM