Question : how to add cookie using a servlet

I am trying to add a cookie using a servlet.  However, when I go Mozilla and check for the cookie being added, it is not there. The browser does not contain the cookie.

Please, see code below. Can someone tell me what I a missing so that the cookie is added to the browser. I am running the application local. Therefore, the new  cookie should be under localhost. I noticed that cookie JSESSIONID gets added by default but mine does not reflect.

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            Cookie cookie = null;
            Cookie[] cookies = request.getCookies(); //get the 20 cookies that can be set by a website.


            UUID cookieID = UUID.randomUUID();

            cookie = new Cookie("cookieTest", cookieID.toString());
            cookie.setMaxAge(315360001);

            response.addCookie(cookie);

        }
        catch(Exception ex)
        {
            String ss = ex.getMessage();
        }
        finally
        {
            //out.close();
        }
    }

Answer : how to add cookie using a servlet

OK - so the code itself works.

Ah - include.

That explains it I am afraid - jsp:include is equivalent to a RequestDispatcher.include which javadoc explicitly says: "The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored." (from http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/RequestDispatcher.html - and it had not changed in newer versions)

The cookie is a header... so you just cannot do it from there.
So you need either to move the cookie somewhere else or to find another way to get the servlet code in the JSP.
Random Solutions  
 
programming4us programming4us