I wanted to store for each user which logs in , his id in Spring session. What I did was:
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
HttpSession session = request.getSession(true);
session.getServletContext().setAttribute("userId", userId);
When I needed the id, i was doing
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
HttpSession session = request.getSession();
Long userId = (Long) session.getServletContext().getAttribute("userId");
First user logs in , get session id is ok.
Second user logs in , the session id is overrwritten ( i see because each next action of first user, gets the user id of second user)
What is the proper way to achieve this, obviously im not understanding the session properly?
Appreciate all the advices
You’re storing the attribute in the
ServletContext, which is shared amongst all sessions of the same webapp.You should be storing the attribute in the
HttpSessionitself:session.setAttribute("userId", userId);Then retrieving it:
Long userId = (Long) session.getAttribute("userId");