简体   繁体   中英

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?

You know the session is from the same user if the id is the same, yes. You can eventually store informations on the session. Alternativelly, you can create session scoped beans :

@Component
@Scope(value="session")
public class MyComponent {
    // ...
}

All you will store in this kind of objects are only accessible by one user.

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.");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM