Java & J2EE Page 4 - The JSP Files (part 6): State Of Grace |
Now, there are innumerable ways to go about creating and reading cookies ona client browser - you can use Javascript, you can use PHP, you can use anyof the wonderful programming languages out there. However, our concern hereis with JSP - so let's take a look at an example which demonstrates how toread and write a cookie. This is a simple hit counter which creates a cookie the first time the uservisits the Web page, and then increments the counter on each subsequentvisit.
Sure, it looks a little complicated - but it won't once we break it downfor you. The first thing you need to know is how to create a cookie on the client -this is accomplished with the following code:
The first two lines create a new instance of a Cookie object - "alpha". Thecookie variable "counter" is then initialized and set to the string "0".Next, the setMaxAge() and setPath() methods of the Cookie object are usedto set the expiry date (in seconds) and the cookie's availability,respectively. Finally, a call to the Response object's addCookie() methodtakes care of actually transmitting the cookie to the client. As already mentioned, the only attribute which is not optional is theNAME=VALUE pair. If you'd like your cookie to remain available even afterthe user closes the browser, you should explicitly set an expiry date; ifnot, the cookie will be destroyed once the browser is closed. The Cookie object also comes with a couple of other interesting methods. setValue(someString) - sets the value of the cookie to someString getValue() - returns the current value of the cookie setPath(someURL) - sets the PATH attribute of a cookie to someURL getPath() - returns the current value of the PATH attribute setMaxAge(someSeconds) - sets the EXPIRES attribute of the cookie, inseconds getMaxAge() - returns the current value of the EXPIRES attribute setDomain(someURL) - sets the DOMAIN attribute of the cookie getDomain() - returns the current value of the DOMAIN attribute setSecure(flag) - sets the SECURE attribute of the cookie as either true orfalse getSecure() - returns the current value of the SECURE attribute Note that you can only save string values in a cookie with setValue() -which entails a lot of string-to-number-to-string conversions if youactually want to store a number (as in this example).
blog comments powered by Disqus |