Why does my Servlet create a JSESSIONID cookie?

user3092110 picture user3092110 · Feb 5, 2014 · Viewed 13.4k times · Source

I am developing something using Servlets. I am creating cookies in this program, and a cookie named as JSESSIONID is being created, but when I comment out all the code even then the cookie is created. Here is my code:

CookieDemoServlet.java:

public class CookieDemoServlet extends HttpServlet {

    public void service(HttpServletRequest req, HttpServletResponse res) throws
            ServletException, IOException {

        /*String em = req.getParameter("email");
        Cookie ck[] = req.getCookies();
        if (ck != null) {
            if (ck.length != 0) {
                for (Cookie c : ck) {
                    String cn = c.getName();

                    if (cn.equals("JSESSIONID")) {

                        System.out.println("You are the Old User");
                        String cv = c.getValue();
                        String d = c.getDomain();

                        System.out.println(cn + "\t:" + cv + "\t:" + d);
                    }

                } else {
                    System.out.println("Sorry,No Cookies Found");
                }
            }

            HttpSession session = req.getSession();
            boolean b = session.isNew();
            if (b) {
                System.out.println("You are the New user");
            } else {
                System.out.println("You are the Old User");
            }

            Cookie c1 = new Cookie("Email", em);
            res.addCookie(c1);
            Cookie c2 = new Cookie("Phone", "99999");
            res.addCookie(c2);*/

            RequestDispatcher rd = req.getRequestDispatcher("cookiedemo.jsp");
            rd.forward(req, res);

        }

    }
}

What could be the reason?

Answer

Koitoer picture Koitoer · Feb 5, 2014

JSESSIONID is managed by J2EE Application servers, it is created in each session that the application server has active, is one of the session tracking mechanism that is used by Servlet API

With this, we can know which sessions (objects) belong to a specific user.

Check this.