使用HttpSession保存用户会话

时间:2017-05-02 07:48:29

标签: spring-mvc session httpsession

我有一个Spring-boot后端,希望在登录时保存我的用户会话,以便在线下再次使用他的信息。

这是我到目前为止尝试这样做的方式:

@RequestMapping(method = RequestMethod.POST, value="/login")
public ResponseEntity<UserInfoMessage> loginUser(@RequestBody UserInfoMessage userInfoMessage, HttpServletRequest request) {
    UserInfoMessage user = mapper.map(userService.login(mapper.map(userInfoMessage)));

    // If our login was a success
    if (user != null) {
        // Save user session
        HttpSession session = request.getSession();
        session.setAttribute("user", user);

        return new ResponseEntity<>(mapper.map(userService.login(mapper.map(userInfoMessage))), HttpStatus.OK);
    } else {
        return new ResponseEntity<>(mapper.map(userService.login(mapper.map(userInfoMessage))), HttpStatus.UNAUTHORIZED);
    }
}

UserInfoMessage是一个存储信息的模型,例如我的用户的电子邮件,姓名等。

此处session.getAttribute("user");正在运作。

但是当我尝试在另一个控制器中检索它时,它是null:

@RequestMapping(method = RequestMethod.POST)
public ProjectInfoMessage createProject(@RequestBody ProjectInfoMessage projectInfoMessage, HttpServletRequest request) {

    HttpSession session = request.getSession();
    System.out.println("User is: " + session.getAttribute("user")); // null

    return mapper.map(projectService.createProject(mapper.map(projectInfoMessage), (UserInfoMessage)session.getAttribute("user")));
}

在会话处理中我不理解什么?

0 个答案:

没有答案