Session is lost and created as new in every servlet request

2022-09-01 00:23:55

I have this big issue. My current session is gone every time I made a new request to Server.

I have checked in a lot of places. I can't find what's the problem. I also have included session-config in web.xml both in tomcat and application. I also enabled to accept cookies to my browsers. Tested in every browser. It's not working.

I am just developing a simple java ee applcation using JSP/Servlet. I am facing the problem only after I have deployed to tomcat in server machine.


答案 1

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 from setting a Cookie for (which would be bad, as it would be the ultimate tracking cookie).evilsite.comcom

So if you access your applicaton via it won't accept any cookie, while for it will accept (and return) the cookie just fine.http://examplehost/http://examplehost.localdomain/

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.


答案 2

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);
}

推荐