Question

I am trying to understand session management in JSP/Servlets using HTTPSession but got confused while visualizing in any web application.So needs clarifications.Suppose I am having one web application using JSP/Servlets. There is a login page.First time when user hits the login page ,through web.xml and application server , request reaches to appropriate servlet.In that servlet , we are getting session object and sessionId and at the same time value of JSESSIONID is also set , provided cookies are not disabled.After validating login credentials ,user is redirected to homepage. My first doubt is when user is redirected to homepage , do we have to explicitly validate the session or implicitly client will validate with the stored JSESSIONID. Now if user clicked on some link in homepage and reaches to second page,do we need to explicitly compare the old stored sessionID both on server and client side.If yes, then we need to store that sessionId and corresponding userId in some kind of static hashmap. Is this approach correct? Kindly clarify if I am undersratnding is wrong.

Was it helpful?

Solution

You don't actually have to mess with the session id itself, unless maybe you are using loadbalancing and this may be needed for that. But if you are just using one server, you don't have to do anything with it yourself. The session id tells your servlet container, lets say Tomcat, where to get the session for this user. So when you call session.getAttribute("username") or session.setAttribute("username", userid) or something like that, it knows which session to pull that from or save it to by the session id. But you only have to deal with the attributes that you store in the session.

To prevent session crossover you can store the user's IP and user-agent in the session and in each page compare the values in the request for IP and user-agent to the ones in the session, and if they don't match, invalidate the session (i.e. session.invalidate()) and redirect to the login page (i.e. response.sendRedirect("loginform.jsp"); return;) since this could mean that someone intercepted someone else' session cookie.

And if you are requiring a user to login, on each page you would want to check that the session attribute containing the username is not null, and redirect to the login page if it is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top