I'm developing a Java based backend and I'm having troubles while managing my user sessions.
I would like to store some personal information for each user in the session, hence I implemented a Servlet for login purpose which creates a session if the login is successful:
@WebServlet("/LoginUserWithPassword")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50) // 50MB
public class LoginUserWithPassword extends HttpServlet {
private static final long serialVersionUID = 1L;
static Logger log = Logger.getLogger(LoginUserWithPassword.class);
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
....
HttpSession session = request.getSession();
session.getServletContext().getContext("/{applicationContextRoot}").setAttribute("nom",usr.nom);
session.getServletContext().getContext("/{applicationContextRoot}").setAttribute("prenom", usr.prenom);
session.getServletContext().getContext("/{applicationContextRoot}").setAttribute("login", usr.email);
session.getServletContext().getContext("/{applicationContextRoot}").setAttribute("id", String.valueOf(usr.id_user));
session.getServletContext().getContext("/{applicationContextRoot}").setAttribute("id_right",String.valueOf(ur.id_right));
session.getServletContext().getContext("/{applicationContextRoot}").setAttribute("right",url.right);
session.getServletContext().getContext("/{applicationContextRoot}").setAttribute("session",session.getId());
then, on the client side (JSP/Javascript), I'm retrieving the session information.
Considering a user1, who is logging successfully on a browser (Chrome) with the following Javascript code:
Glogin = '<%= (String) (request.getSession().getServletContext().getContext("/{applicationContextRoot}").getAttribute("login")) %>';
Gsession = '<%= (String) (request.getSession().getServletContext().getContext("/{applicationContextRoot}").getAttribute("session")) %>';
console.log("login from session: "+Glogin);
console.log("Session ID: "+Gsession);
I can see the following console logs:
login from session: admin3@toto.com
Session ID: 7D6638EA7167580F4C1BD4D51FAD3C9C
Then I'm performing a second login of user2 on the same computer with another browser (FF), I have the following in the console logs:
login from session: admin@toto.com
Session ID: 376C57F6ACB08CD3B66AB8406DB72984
at that stage everything is perfect, I can retrieve my respective attributes on each session,but If I refresh the browser of user1, I retrieve the session ID of user 2....and lose my user1 session context.
Do you have an idea why I'm getting such behavior ? may be my way of implementing session management is not correct ?