Reading and writing cookies in Java Servlets and JSPs
Archive - Originally posted on "The Horse's Mouth" - 2010-02-26 16:49:37 - Graham EllisDo you want to check (and perhaps set) cookies within a Java Servlet? I was looking around for good, straightforward examples today but found that most of the published code is only snippets rather than complete examples, or is over-complex for what should be a simple demo.
First - do you really want to use Cookies directly? If you're looking to save data between a series of accesses that are linked together into a session, Java's HttpSession objects may be what you need. You can store objects into your session, and it's then stored on the server and pulled back when the same visitor returns to carry on his session. There's a complete source code example [here] - an application which lets each user make memo notes, and repeats those notes back each subsequent time the page is called up while the session lasts. Vitally, each user's notes are independent of each other's.
Sessions will be lost when the browser is closed, and expired off the server in a timeout controlled by the web.xml file on the Tomcat Server. If you want your data to be retained longer, per user / browser, then you might want to use a cookie at a lower level. Examples are a shopping site which welcomes you back after several days or weeks, or a site on which you have set user preferences for colour or font size.
Your Cookie based application will want to check for existing cookies before it sets up any new ones, and to do this you run the getCookies method on your request object. It returns an array of Cookie objects, and you can run getName and getValue on each of those objects to see what existing cookies are set. Once you've read your cookies back and analysed them, you may want to set a new cookie - create yourself a Cookie object, giving a name and a value. Then set any other attributes such as how long it is go live for. And finally add it to the response object so that it gets sent.
There's a (new!) complete example of checking and setting a cookie from a Java servlet on our web site - I wrote it about an hour ago with delegates on today's Java Bootcamp Class. Oh - I should provide a link ;-) ... it's [here]