【问题标题】:How to set session attributes in Spring Boot?如何在 Spring Boot 中设置会话属性?
【发布时间】:2018-08-26 07:08:54
【问题描述】:

我想用用户发送的名称设置一个会话属性。用户将首先登录。当他登录时,我希望他的用户名将设置为会话属性。

我该怎么办?

这是我的控制器:

@GetMapping("/login")
public String login() {
    return "Login";
}

@PostMapping("/loginCheck")
public String checkLogin(@ModelAttribute("users") Users user) {
    if (userService.checkUser(user)) {
        return "redirect:/"+user.getUsername()+"/";
    } else {
        return "Login";
    }
}

@PostMapping("/signup")
public ModelAndView createuser(@ModelAttribute("users") Users user) {
    if (userService.checkUser(user)) {
        return new ModelAndView("Login");
    } else {
        userService.adduser(user);
        return new ModelAndView("Login");
    }
}


现在我如何将用户名设置为我在user.getUsername() 中获得的会话?

【问题讨论】:

    标签: java spring-boot session httpsession


    【解决方案1】:

    在 SpringMVC 中,您可以通过将 HttpSession 作为参数添加到方法中来自动注入 HttpSession。因此,您的登录可能类似于:

    @GetMapping("/login")
    public String login(@ModelAttribute("users") Users user, HttpSession session)
    {
        if(userService.authUser(user)) { //Made this method up
            session.setAttribute("username", user.getUsername());
            view.setViewName("homepage"); //Made up view
        }
        else{
            return new ModelAndView("Login");
        }
    }
    

    【讨论】:

      【解决方案2】:
      @Autowired
      ObjectFactory<HttpSession> httpSessionFactory;
      .
      .
      .
      HttpSession session = httpSessionFactory.getObject();
      

      Works good. Thanks to this post.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-21
        • 2019-01-03
        • 2015-09-03
        • 2019-03-04
        • 2020-12-24
        • 2012-12-23
        • 2017-01-08
        相关资源
        最近更新 更多