httpsessionsession-management

How does session managment work in spring?


I can't really understand the concept of this. Take a look what I have:

@PostMapping("/login")
public ModelAndView login( @ModelAttribute UserLoginDTO userDto, HttpSession session) {
    if (authenticateService.loginCheck(userDto.getUsername(), userDto.getPassword())) {
        session.setAttribute("sessionid",123);
        return new ModelAndView("redirect:/profile");
    } else {
        return new ModelAndView("signin","error","Invalid username or password combination, or the user does not exist.");
    }
}

I have set a sessionID to the session. When the user navigates around the website, how do I know that it is the same user?

Do I have to store the sessionID on server side in a ConcurrentHashMap? And when there is a page switch I should do this?

if (conHashMap[...] == session.getId()) {...}
else //redirect to login page 

Also on logout, do I just remove the element from the hashmap and call for session.invalidate()?

Or is there a way of doing this without using hashmaps at all?


Solution

  • Figured it out.

    After invalidating, the browser will visit the site with a new session. The new session won't have the "sessionid" attribute bound to it. This way, I could determine which session is a valid one, without using hashmaps.

    if (session.getAttribute("sessionid")==null){
            return new ModelAndView("signin","error","Session expired, please log in again.");