【问题标题】:difference in doing "model.addAttribute()" and "session.setAttribute()"做“model.addAttribute()”和“session.setAttribute()”的区别
【发布时间】:2020-09-25 08:32:46
【问题描述】:

有人能告诉我使用“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";
        }
    }

'''

【问题讨论】:

    标签: java spring database jsp model-view-controller


    【解决方案1】:

    主要区别在于模型是每个请求,而会话是每个 Http 会话。这意味着每个请求都会有一个新模型。处理请求后模型将被销毁,并为下一个请求创建一个全新的模型。

    因此,如果您希望后续请求可以访问您在同一会话中的先前请求中设置的值,则必须将其添加到会话而不是模型中。

    【讨论】:

    • 感谢您的回答。有用且易于理解。
    • @shrumsowen11 如果答案解决了您的问题,请考虑接受答案
    • 我是 Stack Overflow 的新手,不知道这一点,现在被接受了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    相关资源
    最近更新 更多