Reputation: 1237
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
Upvotes: 3
Views: 5388
Reputation: 1590
I prefer saving sessionBean object in HttpSession ... you can create bean with data which you want to keep in session
session.setAttribute("sessionData",sessionBean);
Upvotes: 0
Reputation: 11705
You're not using the HttpSession
here, you're using the ServletContext
, as the name implies, which is a singleton.
session.setAttribute("userId", userId);
Long userId = (Long) session.getAttribute("userId");
Upvotes: 1
Reputation: 32054
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 HttpSession
itself:
session.setAttribute("userId", userId);
Then retrieving it:
Long userId = (Long) session.getAttribute("userId");
Upvotes: 5