Search code examples
javaspring-mvcspring-boothttpsession

HttpSession in Springboot


I have two controllers. I'm trying to put the logged user into the session in one method, and then get it in a other method. But the sessions are different, how to fix it?

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/user/signIn", method = RequestMethod.POST)
    public ResponseEntity<DataUser> signIn(@RequestBody @Valid SignInUser signInUser,
                                           HttpSession session) {
        User user = userService.getUser(signInUser.getEmail(), signInUser.getPassword());
        session.setAttribute("user", user);
        DataUser dataUser = new DataUser((User) session.getAttribute("user"));
        return ResponseEntity.ok(dataUser);
    }

}

@RestController
public class MessageController {

    @Autowired
    private MessageService messageService;

    @RequestMapping(value = "/data/message", method = RequestMethod.POST)
    public Message save(@RequestBody NewMessage newMessage,
                        HttpSession session) {
        System.out.println(session.getAttribute("user"));
        Message message = new Message(newMessage);
        LocalDateTime dateTime = LocalDateTime.now();
        message.setDateTime(dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
        message.setNumberRating(0);
        return messageService.save(message);
    }

}

session.getAttribute("user") is null


Solution

  • The common behavior of sessions for WebApps is that your client is identified, commonly through a cookie called JSESSIONID, but for REST calls you do not have such possibility you probably don't even call from a browser, so you can not say that one request is coming from the same "machine/user" as this other request.

    In order to do that you'll need to:

    • Properly configure and enable spring session
    • Have a way identify your requests, unique IDs of some sort.

    And every new request have to inform you the same identificator, so you can ask for spring something like "give me the session for this user".

    Here is a more detailed tutorial for Spring Session.