Session is lost and created as new in every servlet request
One possible cause for this is having a "naked" host name (i.e. one without a domain part). That's fairly common if you're working in an Intranet.
The problem is that almost all browsers cookies will not accept cookies for hostnames without a domain name. That's done in order to prevent evilsite.com
from setting a Cookie for com
(which would be bad, as it would be the ultimate tracking cookie).
So if you access your applicaton via http://examplehost/
it won't accept any cookie, while for http://examplehost.localdomain/
it will accept (and return) the cookie just fine.
The nasty thing about that is that the server can't distinguish between "the browser got the cookie and ignored it" and "the browser never got the cookie". So each single access will look like a completely new sesson to the server.
First check if the webapp's context.xml
does not have cookies="false"
configured.
Further it's good to know that cookies are domain, port and contextpath dependent. If the links in the page points to a different domain, port and/or contextpath as opposed to the current request URL (the one you see in the browser's address bar), then the cookie won't be passed through which will cause that the session cannot be identified anymore and thus you will get a new one from the servletcontainer.
If that is not the cause, then check if you aren't doing a redirect on every request using HttpServletResponse.sendRedirect()
for some reason. If you do this already on the very first request, then the cookie will get lost. You'll need to replace
response.sendRedirect(url);
by
response.sendRedirect(response.encodeRedirectURL(url));
After years, I never posted the answer back here. At that time I was busy and forgot about this question. But, today I am looking for a solution in Stackoverflow as usual and saw this notification mentioning I am getting points from this Question. Seems like other developers are facing the same issue. So, I tried to recall how I solved the issue. And yes, I solved by manually put back the session id to track/maintain the session id.
Please see the code that I manually put back jsessionid inside the servlet.
HttpSession session = request.getSession();
if (request.getParameter("JSESSIONID") != null) {
Cookie userCookie = new Cookie("JSESSIONID", request.getParameter("JSESSIONID"));
response.addCookie(userCookie);
} else {
String sessionId = session.getId();
Cookie userCookie = new Cookie("JSESSIONID", sessionId);
response.addCookie(userCookie);
}