This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes Not able to set cookies Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "Not able to set cookies" Watch "Not able to set cookies" New topic
Author

Not able to set cookies

Sony Agrawal
Ranch Hand

Joined: Oct 04, 2009
Posts: 143
HI i am trying to learn about cookie ... I am trying to setcookies but not able to...Please let me know the issue... Browser is enable to accept the cookies...
HTML


SERVLET



JSP


Its printing :"NO COOKIES"



I have a opened this thread in servlets forum , which i guess is correct forum
somebody please close this thread
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9307
    
  17

There are 2 problems with your code.
1) Since you are forwarding the request after setting the cookie, your cookie is deleted. Any headers or cookies that you set before the forward method are deleted. If the header/cookie is sent to the client before you call the forward, you'll get the IllegalStateException.
2) The way you are checking the cookie is not right. To test the cookie, you must send the response once to the client before checking if the cookies exist. If you set cookies on the server side and check for cookies directly on the server, there won't be any cookies. Let me explain it in simpler language. The first request is received by the servlet, there aren't any cookies in the request object. You set the cookies in the response object, this doesn't mean that the request object will now contain those cookies. The cookies will come in the next request from the browser. So the correct code would be something like this

When you first request this servlet, you won't get any cookies, on the next request you'll be able to see the cookie in the output...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9307
    
  17

Since cookies are a part of SCWCD exam, this is also the correct forum for the question. Since the other thread doesn't have any replies, I'll close that one instead of this one...
Sony Agrawal
Ranch Hand

Joined: Oct 04, 2009
Posts: 143
Thanks ankit... i missed the actual point....thanks for bring it up
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Not able to set cookies