Search code examples
javasessionservletscookiesjsessionid

Session Handling in servlet using JSESSIONID cookie not getting session


I read that to persist session in servlet a cookie gets saved at client side with the name of JSESSIONID.

I checked it also and I found the cookie of localhost with the name of JSESSIONID with some random String value.

So I tried to create the session manually by creating the JSESSIONID cookie in the servlet but when I am trying to get the session it's not working.

What is happening here?

Is there anything else other than cookie(JSESSIONID) that gets stored soomewhere for the session creation?

If not why I'm not able to get the session ?

Please Help.

Code that I used to create the cookie and get the session

package sessionHandling;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/sessionhandling")
public class SessionHandling extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ServletOutputStream out = response.getOutputStream();
    out.print("Hello Mr.! How are you?");
    HttpSession session = request.getSession(false);
    if(session != null){
        out.println("You are logged in.");

        out.println("session found with "+session.getId());
        out.println("session found with "+session.getLastAccessedTime());

    }else{
        //session = request.getSession(true);
        Cookie JSESSIONID = new Cookie("JSESSIONID", "12345");
        JSESSIONID.setMaxAge(-1);
        response.addCookie(JSESSIONID);
        System.out.println("Cookie Created");

        out.print("You are not logged in");
    }
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
}

}

Solution

  • You're not responsible for creating or tracking the cookie. The servlet container looks after this for you.

    As soon as you invoke:

       HttpSession session = request.getSession(true);
    

    or

       HttpSession session = request.getSession();
    

    then the servlet container will start maintaining the session for you (and generate the cookie as needed).

    The HttpSession object is maintained in server memory between requests and is usually looked up by the session id. If you create the cookie yourself the server will not know anything about it or any associated HttpSession.